I have a $.each jQuery function sitting in a parent javascript function, how do I break the parent function upon a certain index (i)?
"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."
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.
Using return to exit a function in javascript Using return is the easiest way to exit a function. You can use return by itself or even return a value.
jQuery's each() function is used to loop through each element of the target jQuery object — an object that contains one or more DOM elements, and exposes all jQuery functions. It's very useful for multi-element DOM manipulation, as well as iterating over arbitrary arrays and object properties.
To break from one loop, just return false
:
$('something').each(function() {
if (need_to_break) {
return false; // returning false stops the loop
}
});
To break from / return from multiple each
loops at once, just throw an exception:
var $break = {};
$('something').each(function() {
try {
$('something').each(function() {
$('something').each(function() {
$('something').each(function() {
throw $break;
});
});
});
} catch(E) {
if (E != $break) throw E;
}
});
And catch it in the loop you want to return to.
This is how Prototype.js implements break
, in their Enumerable.each()
, for instance.
A more conventional solution:
var do_break = false;
$('something').each(function() {
$('something').each(function() {
$('something').each(function() {
$('something').each(function() {
do_break = true;
return false;
});
if (do_break) {
return false;
}
});
if (do_break) {
return false;
}
});
if (do_break) {
return false;
}
});
From the sound of it, you have something like this:
function outer(someParam) {
$.each(someParam, function(i) {
// do something with each value in someParam
});
}
You want to return from outer
when the inner loop reaches a certain value. You can't do this in one go. The key point is that doing return false
from the $.each
callback ends the "loop". You can then set a variable to return conditionally if you need that:
function outer(someParam) {
var returnNow = false;
$.each(someParam, function(i) {
if (i === 5) {
returnNow = true;
return false;
}
// do something with each value in someParam
});
if (returnNow) {
return;
// return immediately
}
// do some other action if you want to
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With