1

我正在使用下面的代码来检查一些表单字段并在单击按钮时呈现数据表。如果任何字段为空,我的意图是停止呈现表格。显然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

});
4

2 回答 2

3

如果你仔细看,你return false$.each回调函数里面,所以它returns false是那个函数的调用者,而不是你所在的“主函数”。

试试这个:

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

});
于 2012-06-24T14:15:48.733 回答
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
  }

});
于 2012-06-24T14:14:51.317 回答