简体   繁体   English

在.each()循环内失败时中断jQuery函数执行

[英]Break jQuery function execution on failure inside .each() loop

I have the following form 我有以下表格

<input class="required" id="name" value="some content"/>
<input class="required" id="address" value=""/>
<input class="required" id="lastname" value="some content"/>

and the following jQuery function. 以及以下jQuery函数。 It contains a .each() loop to check some inputs. 它包含一个.each()循环来检查某些输入。 When the check fails, the function should break and return false . 当检查失败时,该函数应中断并返回false

function check() {
  $('.required').each(function() {
    var input = $(this);
    console.log(input.attr('id'));

    if (input.val() == null || input.val() == '') {
      console.log('*** Failed ***');
      return false;
    }
  });

  console.log('Other code');
  return true;
}

Unfortunately, when I run the code I see the following output: 不幸的是,当我运行代码时,我看到以下输出:

name
address
*** Failed ***
Other code

The .each() loop correctly stops after the first failure, but the check function seems to keep running. 第一次失败后, .each()循环正确停止,但是检查功能似乎一直在运行。 How can I break its execution? 如何中断执行? Here's a jsFiddle . 这是一个jsFiddle

function check() {
  var valid = true;
  $('.required').each(function() {
    var input = $(this);
    console.log(input.attr('id'));

    if (input.val() == null || input.val() == '') {
      console.log('*** Failed ***');
      valid = false;
      return false;
    }
  });

  if (!valid) return false;

  console.log('Other code');
  return true;
}

return false仅会破坏$.each语句,但是该函数会继续执行下一条指令( console.log('Other code'); )。

I've found an alternative solution. 我找到了替代解决方案。 The idea is to get the .required inputs and then make a classic for loop. 这个想法是获取.required输入,然后制作经典的for循环。 This avoids the each() loop and the anonymous function. 这避免了each()循环和匿名函数。

function check() {
  var required = $('.required');
  var size = required.size();

  for (var i = 0; i < size; i++) {
    var input = $(required[i]);
    console.log(input.attr('id'));

    if (input.val() == null || input.val() == '') {
      console.log('*** Failed ***');
      return false;
    }
  }

  console.log('Other code');
  return true;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM