1

我有变量

var student_office_id = $(this).data('office');

我希望在 jQuery validate 插件中使用它,如下所示:

$('.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

我在控制台中收到以下错误:Uncaught SyntaxError: Unexpected identifier

它指的是我尝试附加 student_office_id 的第一行,我想它也会在其他实例上返回错误。

4

1 回答 1

1

您不能以这种方式使用变量指定对象中的键。您需要执行以下操作:

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
});

关键是您可以使用类似数组的[]语法和字符串来访问对象的属性,这将允许您使用另一个变量的值动态生成键(作为字符串)。

于 2012-08-06T15:44:12.407 回答