附加变量使用jQuery的验证插件
问题描述:
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_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
});
关键的一点是,你可以使用类似数组的[]
语法与琴弦上的对象访问属性,这将允许你动态地生成密钥(作为字符串)使用另一个变量的值。
你可以粘贴'console.log(student_office_id)'的结果吗? – Florent 2012-08-06 15:42:37