Breaking parent function of jQuery each function
I have a $.each jQuery function sitting in a parent javascript function, how do I b开发者_JS百科reak the parent function upon a certain index (i)?
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
}
The only solution I can think of is setting a variable(switch) on the parent function, in the each function, if i==x, break out of the each function first after changing the switch... then check for the switch value to determine whether to break out of the parent function.
you would do something like:
function foo() {
var success = true;
$('element').each(function() {
if (condition) {
success = false;
return success;
}
});
if (!success)
return false;
//should not get here
}
Labeled Break
outerloop:
for (;;)
{
for (;;)
{
break; /* breaks inner loop */
}
for (;;)
{
break outerloop; /* breaks outer loop */
}
}
精彩评论