我想创建一个对象,其第一个属性是一个函数,用于确定父对象访问哪个子对象。我的具体应用是根据提交的表单类型更改使用的表单验证类型。
我在页面加载时收到的错误消息是:Uncaught TypeError: Cannot set property 'validate' of undefined
到目前为止这是我的Javascript(这里是JSfiddle:http://jsfiddle.net/WJRwv/3/):
var O={
form:{
voting:{
validate: {}, success: {}
},
delete:{
validate: {}, success: {}
}
}
};
O.form=function(formType){
if(formType=='voting'){
return O.form.voting;
}
else if(formType=='delete'){
return O.form.delete;
}
}
以下直线导致错误
O.form.voting.validate=function($form){ //**THIS LINE IS CAUSING THE ERROR**
if($form.validate().form()){ // this is a method from the jQuery validate plugin
console.log('YES validates');
}
else {
console.log('NOT valid'); return false;
}
}
$('input[type=submit]').click(function(){
var formType=$(this).data('form-type'),
$form=$(this).closest('form'),
formType=O.form(formType);
console.log('form type is:'+formType);
formType($form); //this should call the O.form.voting.validate method
});
HTML:
<form>
<input type="submit" data-form-type='voting' name='voting' value="1">
</form>
<form>
<input type="submit" data-form-type='delete' name='delete' value="1">
</form>
答案 0 :(得分:4)
问题是您之前使用函数覆盖了o.form
,因此o.form.voting
(以及您最初设置的其他内容)不再存在。
答案 1 :(得分:1)
这导致了问题:
O.form=function
现在form
不再具有voting
属性。
答案 2 :(得分:1)
O.form
功能正在覆盖您的O.form
对象文字。代替...
var O = {
form: function(formType) {
if(formType=='voting'){
return O.form.voting;
}
else if(formType=='delete'){
return O.form.delete;
}
}
};
O.form.voting = {
validate: {}, success: {}
};
O.form.delete = {
validate: {}, success: {}
};
答案 3 :(得分:0)
你可以做的是创建一个将表单映射到验证器设置的函数,jQuery验证器允许每个表单验证器,并确定在提交表单时使用哪个验证器......
更新了HTML ...
<form data-form-type="voting">
<input type="submit" name="voting" value="1"/>
</form>
<form data-form-type="delete">
<input type="submit" name="delete" value="1"/>
</form>
更新了JS ......
var o = {};
o.setFormValidations = function(types) {
// Loop through forms and attempt to map each form to an item in the passed
// types argument
$("form").each(function() {
// Get the form type from the data attribute
var type = $(this).data("form-type");
// Add in the validator if there is a matching item in the passed
// types arguments
if(types[type]) {
$(this).validate(types[type]);
}
});
};
// On document ready we run the function passing in the jQuery validator
// settings for each form type
$(function() {
namespace.setFormValidations({
"voting" : {
rules: {},
messages: {},
submitHandler: function() {
// Do something for a valid form
}
},
"delete" : {
rules: {},
messages: {},
submitHandler: function() {
// Do something for a valid form
}
}
});
});