How do I break out of an $.each in jquery?
How to I break out of the following jquery each method when a condition is met;
var rainbow = {'first' : 'red', 'second' 开发者_运维问答: 'orange', 'third' : 'yellow'};
$.each(rainbow, function (key, color) {
if (color == 'red') {
//do something and then break out of the each method
alert("i'm read, now break.");
}
});
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.
var rainbow = {'first' : 'red', 'second' : 'orange', 'third' : 'yellow'};
$.each(rainbow, function (key, color) {
if (color == 'red') {
//do something and then break out of the each method
alert("i'm read, now break.");
return false;
}
});
As explicitly written on jQuery's page for $.each
:
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.
Please google the terms you search before posting here ! It's a pity that jQuery has one of the best documentations ever if you do not bother to read about it !
The JQuery documentation for each states:
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.
It also provides examples.
<script>
var arr = [ "one", "two", "three", "four", "five" ];
jQuery.each(arr, function() {
$("#" + this).text("Mine is " + this + ".");
return (this != "three"); // will stop running after "three"
});
</script>
Try this
http://api.jquery.com/jQuery.each/
We can not use Break and Continue in jquery functions
Try this
var rainbow = {'first' : 'red', 'second' : 'orange', 'third' : 'yellow'};
$.each(rainbow, function (key, color) {
if (color == 'red') {
//do something and then break out of the each method
alert("i'm read, now break.");
return false;
}
alert(color);
});
精彩评论