2012-08-06 57 views
1

我有可變附加變量使用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的第一行,我想它會在其他實例上返回一個錯誤。

+0

你可以粘貼'console.log(student_office_id)'的結果嗎? – Florent 2012-08-06 15:42:37

回答

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

關鍵的一點是,你可以使用類似數組的[]語法與琴絃上的對象訪問屬性,這將允許你動態地生成密鑰(作爲字符串)使用另一個變量的值。