有没有一种方法可以使用循环来创建10个这样的循环,并在所有有"1“的地方递增
//1
$('#catbudgetform1').validate({
errorPlacement: function(error, element) {},
rules: {budgTotal1: { required: true, money:true }},
submitHandler:function() {
var theForm = $('#catbudgetform1');
updateSuccess(theForm,1);
},
invalidHandler: function(){
alert('Valid Number (ex. 1234 or 1234.00) is Required');
}
});**注意#catgetform1和budgTotal1需要是#catgetform2和budgTotal2,依此类推
或者,有没有一种方法可以将验证独立地应用于十个表单中的每一个,而不需要编写十次?
发布于 2012-03-28 22:53:10
我会尝试只使用类,不使用in,并且在submitHandler中使用$(this).closest("form")而不是$("#catbudgetform1")
$('.catbudgetform').each(function(i){
$(this).validate({
errorPlacement: function(error, element) {},
rules: {"budgTotal" + i: { required: true, money:true }},
submitHandler:function() {
var theForm = $(this).parents("form");
updateSuccess(theForm,i);
},
invalidHandler: function(){
alert('Valid Number (ex. 1234 or 1234.00) is Required');
}
});
});发布于 2012-03-28 23:02:47
解决此问题的一种更简单的方法是将元素从具有唯一ID更改为具有特定的类。这极大地简化了您的逻辑,因为一个类允许分组,而这正是您在这里想要的。
$('.catbudgetform').each(function (index) {
var theRules = {};
theRules['budgTotal' + index] = { required: true, money:true };
$(this).validate({
errorPlacement: function(error, element) {},
rules: theRules,
submitHandler:function() {
var theForm = $(this);
updateSuccess(theForm, index);
},
invalidHandler: function(){
alert('Valid Number (ex. 1234 or 1234.00) is Required');
}
});
});发布于 2012-03-28 23:00:26
我会尝试像Flöcsy建议的那样做一些事情,但是因为听起来你已经有一些代码在其中硬编码了索引,下面的代码就可以了。
for (var i=1; i <= 10; i++) {
// Freeze the loop variable with a self calling function
(function(index){
// Can't do a literal object if the property is dynamic
var rules = {};
rules['budgTotal'+index] = { required: true, money:true };
$('#catbudgetform' + index).validate({
errorPlacement: function(error, element) {},
rules: rules,
submitHandler:function() {
var theForm = $('#catbudgetform' + index);
updateSuccess(theForm,index);
},
invalidHandler: function(){
alert('Valid Number (ex. 1234 or 1234.00) is Required');
}
});
})(i); // Passing the loop variable into the anonymous self calling function
} https://stackoverflow.com/questions/9910047
复制相似问题