How to break out of jQuery each loop?
To break
a $.each
or $(selector).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; // breaks
}
});
// or
$(selector).each(function() {
if (condition) {
return false;
}
});
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.