我有变量
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
我在控制台中收到以下错误:未捕获的语法错误:意外的标识符
它指的是我尝试附加 Student_office_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
});
关键点是,您可以使用类似数组的 []
语法和字符串来访问对象的属性,这将允许您使用另一个变量的动态生成键(作为字符串)值。
关于javascript - 附加要使用的变量 jQuery 验证插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11831488/