使用jQuery.each()时返回一个值?

Pra*_*ani 34 each jquery

如果我找到第一个空白文本框,我想返回false并从函数返回

function validate(){
 $('input[type=text]').each(function(){
   if($(this).val() == "")
     return false;
});
}
Run Code Online (Sandbox Code Playgroud)

以上代码对我不起作用:(任何人都可以帮忙吗?

Nic*_*ver 61

你正在跳出来,但是从循环开始,我会使用一个选择器来进行特定的"无价值"检查,如下所示:

function validate(){
  if($('input[type=text][value=""]').length) return false;
}
Run Code Online (Sandbox Code Playgroud)

或者,当您去内环路,并返回结果设置结果从外循环:

function validate() {
  var valid = true;
  $('input[type=text]').each(function(){
    if($(this).val() == "") //or a more complex check here
      return valid = false;
  });
  return valid;
}
Run Code Online (Sandbox Code Playgroud)


T.J*_*der 14

你可以这样做:

function validate(){
    var rv = true;
    $('input[type=text]').each(function(){
        if($(this).val() == "") {
            rv = false;   // Set flag
            return false; // Stop iterating
        }
    });
    return rv;
}
Run Code Online (Sandbox Code Playgroud)

true如果您没有找到它,则假定您想要返回.

您可能会发现这是您不想使用each的一些注意事项:

function validate(){
    var inputs = $('input[type=text]');
    var index;
    while (index = inputs.length - 1; index >= 0; --index) {
        if (inputs[index].value == "") { // Or $(inputs[index]).val() == "" if you prefer
            return false;
        }
    }
    // (Presumably return something here, though you weren't in your example)
}
Run Code Online (Sandbox Code Playgroud)