我使用下面的代码检查一些表单字段并在按钮单击时呈现数据表。我的目的是在任何字段为空时停止呈现表。显然,循环中的return false
无效。
这是正确的方法吗?有更好的方法吗?
$('#advance_search').click(function(){
var ds = $('.advance_search .filter_field');
$.each(ds, function(index, value){ //this loop checks for series of fields
if ($(this).val().length === 0) {
alert('Please fill in '+$(this).data('label'));
return false;
}
});
dt.fnDraw(); //shouldn't be called if either one of the field is empty
});
答案 0 :(得分:3)
如果仔细观察,return false
位于$.each
回调函数内,所以returns false
表示该函数的调用者,而不是您所在的“主函数”。< / p>
试试这个:
$('#advance_search').click(function(){
var ds = $('.advance_search .filter_field'), valid = true;
$.each(ds, function(index, value){ //this loop checks for series of fields
if($(this).val().length === 0) {
alert('Please fill in '+$(this).data('label'));
return (valid = false); //return false and also assign false to valid
}
});
if( !valid ) return false;
dt.fnDraw(); //shouldn't be called if either one of the field is empty
});
答案 1 :(得分:0)
您可以添加控制变量以防止调用dt.fnDraw()
:
$('#advance_search').click(function(e){
e.preventDefault();
var check = 0, // Control variable
ds = $('.advance_search .filter_field');
$.each(ds, function(index, value){ //this loop checks for series of fields
if($(this).val().length === 0) {
check++; // error found, increment control variable
alert('Please fill in '+$(this).data('label'));
}
});
if (check==0) { // Enter only if the control variable is still 0
dt.fnDraw(); //shouldn't be called if either one of the field is empty
}
});