How to break out of jQuery each Loop

How do I break out of a jQuery each loop?

I have tried:

 return false;

In the loop but this did not work. Any ideas?

UPDATE While it's not clear what the original scope of the question was, please beware that the chosen answer only covers the $.each() function but not the $().each .


To break a $.each loop, you have to return false in the loop callback.

Returning true skips to the next iteration, equivalent to a continue in a normal loop.

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

Break out of a $().each loop is covered in How to break/exit from a each() function in JQuery?


According to the documentation return false; should do the job.

We can break the $.each() loop [..] by making the callback function return false.

Return false in the callback:

function callback(indexInArray, valueOfElement) {
  var booleanKeepGoing;

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

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

BTW, continue works like this:

Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.


I created a Fiddle for the answer to this question because the accepted answer is incorrect plus this is the first StackOverflow thread returned from Google regarding this question.

To break out of a $.each you must use return false;

Here is a Fiddle proving it:

http://jsfiddle.net/9XqRy/

链接地址: http://www.djcxy.com/p/36322.html

上一篇: 打破嵌套for循环

下一篇: 如何摆脱每个循环的jQuery