Javascript 附加要使用的变量jQuery验证插件
我有一个变量Javascript 附加要使用的变量jQuery验证插件,javascript,jquery,jquery-validate,Javascript,Jquery,Jquery Validate,我有一个变量 var student_office_id = $(this).data('office'); 我希望在jQuery验证插件中使用它,如下所示: $('.office_directed_to, .degree_type').bind('change', function() { var student_office_id = $(this).data('office'); $("#admin-form").validate({ rules: {
var student_office_id = $(this).data('office');
我希望在jQuery验证插件中使用它,如下所示:
$('.office_directed_to, .degree_type').bind('change', function() {
var student_office_id = $(this).data('office');
$("#admin-form").validate({
rules: {
"h_number["+student_office_id+"]": {
required: function(element) {
return $("#office_directed_to-8").val() != '';
}
},
"degree_type["+student_office_id+"]": {
required: function(element) {
return $("#office_directed_to-"+student_office_id+).val() != '';
}
}
} // end rules
}); // end validate
}); // end bing change
我在控制台中收到以下错误:未捕获SyntaxError:意外标识符
它指的是我试图在其中添加student\u office\u id的第一行,我想它在其他实例上也会返回一个错误。您不能以这种方式使用变量在对象中指定键。您需要执行以下操作:
var rules = {}
rules["h_number["+student_office_id+"]"] = {
required: function(element) {
return $("#office_directed_to-8").val() != '';
}
}
rules["degree_type["+student_office_id+"]"] = {
required: function(element) {
return $("#office_directed_to-"+student_office_id+"").val() != '';
}
}
$("#admin-form").validate({
rules: rules // end rules
});
关键的一点是,您可以使用类似于字符串的数组语法来访问对象的属性,这将允许您使用另一个变量的值动态生成键(作为字符串)。您不能以这种方式使用变量在对象中指定键。您需要执行以下操作:
var rules = {}
rules["h_number["+student_office_id+"]"] = {
required: function(element) {
return $("#office_directed_to-8").val() != '';
}
}
rules["degree_type["+student_office_id+"]"] = {
required: function(element) {
return $("#office_directed_to-"+student_office_id+"").val() != '';
}
}
$("#admin-form").validate({
rules: rules // end rules
});
关键的一点是,您可以使用类似于
[]
的数组语法和字符串来访问对象的属性,这将允许您使用另一个变量的值动态生成键(作为字符串)。您可以粘贴console.log(学生办公室id)
的结果吗?您可以粘贴console.log的结果吗(学生办公室id)
?