如何跳出jQuery每个循环?

我尝试过:

 return false;

但这不起作用。有什么想法吗?


更新日期:2020年9月5日

我将返回设置为假;在错误的地方。当我把它放到循环中时,一切都正常了。


要中断$.each或$(选择器).each循环,必须在循环回调中返回false。

返回true将跳转到下一次迭代,相当于正常循环中的continue。

$.each(array, function(key, value) { 
    if(value === "foo") {
        return false; // breaks
    }
});

// or

$(selector).each(function() {
  if (condition) {
    return false;
  }
});

根据文件返回错误;应该完成这项工作。

我们可以通过调用回调函数来打破$.each()循环[..]返回false。

在回调中返回false:

function callback(indexInArray, valueOfElement) {
  var booleanKeepGoing;

  this; // == valueOfElement (casted to Object)

  return booleanKeepGoing; // optional, unless false 
                           // and want to stop looping
}

顺便说一下,继续这样做:

返回非false与for循环中的continue语句相同;它将立即跳到下一次迭代。

我为这个问题的答案创建了一个Fiddle,因为接受的答案不正确,加上这是Google返回的关于这个问题的第一个StackOverflow线程。

要突破$.each,必须使用return false;

这里有一个Fiddle证明了这一点:

http://jsfiddle.net/9XqRy/

我遇到了这样一种情况,即我遇到了一个打破循环的条件,但是.each()函数之后的代码仍然执行。然后,我将一个标志设置为“true”,并在.each()函数之后立即检查标志,以确保后面的代码没有执行。

$('.groupName').each(function() {
    if($(this).text() == groupname){
        alert('This group already exists');
        breakOut = true;
        return false;
    }
});
if(breakOut) {
    breakOut = false;
    return false;
} 

“each”使用回调函数。回调函数的执行与调用函数无关,因此不可能从回调函数返回到调用函数。

如果您必须基于某些条件停止循环执行并保持在同一函数中,请使用for循环。

我知道这是一个相当古老的问题,但我没有看到任何答案,这说明了为什么以及何时可能与回报决裂。

我想用两个简单的例子来解释:

1.示例:在这种情况下,我们有一个简单的迭代,如果我们能找到这三个,我们想用return true打破。

function canFindThree() {
    for(var i = 0; i < 5; i++) {
        if(i === 3) {
           return true;
        }
    }
}

如果我们调用这个函数,它只会返回true。

2.示例在本例中,我们希望使用jquery的each函数进行迭代,该函数将匿名函数作为参数。

function canFindThree() {

    var result = false;

    $.each([1, 2, 3, 4, 5], function(key, value) { 
        if(value === 3) {
            result = true;
            return false; //This will only exit the anonymous function and stop the iteration immediatelly.
        }
    });

    return result; //This will exit the function with return true;
}

我用这种方式(例如):

$(document).on('click', '#save', function () {
    var cont = true;
    $('.field').each(function () {
        if ($(this).val() === '') {
            alert('Please fill out all fields');
            cont = false;
            return false;
        }
    });
    if (cont === false) {
        return false;
    }
    /* commands block */
});

如果cont不是false,则运行命令块