How to use continue in jQuery each() loop?
JqueryFor LoopEachJquery Problem Overview
In my application i am using AJAX call. I want to use break
and continue
in this jQuery loop.
$('.submit').filter(':checked').each(function() {
});
Jquery Solutions
Solution 1 - Jquery
We can break both a $(selector).each()
loop and a $.each()
loop at a particular iteration by making the callback function return false
. Returning non-false
is the same as a continue statement in a for
loop; it will skip immediately to the next iteration.
return false; // this is equivalent of 'break' for jQuery loop
return; // this is equivalent of 'continue' for jQuery loop
Note that $(selector).each()
and $.each()
are different functions.
References:
- [$(selector).each()][1]
- [$.each()][2]
- [What is the difference between $.each(selector) and $(selector).each() ][3]
[1]: http://api.jquery.com/each/ "$(selector).each()" [2]: http://api.jquery.com/jquery.each/ "$.each()" [3]: https://stackoverflow.com/questions/6611190/what-is-the-difference-between-eachselector-and-selector-each "What is the difference between $.each(selector) and $(selector).each()"
Solution 2 - Jquery
$('.submit').filter(':checked').each(function() {
//This is same as 'continue'
if(something){
return true;
}
//This is same as 'break'
if(something){
return false;
}
});
Solution 3 - Jquery
return or return false are not the same as continue. If the loop is inside a function the remainder of the function will not execute as you would expect with a true "continue".
Solution 4 - Jquery
> We can break the $.each() loop at a particular iteration by making the > callback function return false. Returning non-false is the same as a > continue statement in a for loop; it will skip immediately to the next > iteration. -- jQuery.each() | jQuery API Documentation