我想创建一个对象,其第一个属性是一个函数,该函数确定父对象访问哪个子对象。我的特定应用程序正在根据提交的表单类型更改使用的表单验证类型。
我在页面加载时收到的错误消息是: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>