Javascript/JQuery: return immediately from PARENT function in call to each() via anon function
For example:
> function foo() {
> jQuery(wh开发者_开发知识库atever).each( function() {
return; // this just exits the anonymous function - is there a way to return from foo?
}
);
>
> }
**Correction: Added more detail. Use a flag to allow returning from the PARENT function **
function foo() {
var doreturn = false;
jQuery(whatever).each( function() {
if(youwanttoreturn){
doreturn=1;
return false;
}
});
if(doreturn)return;
}
http://api.jquery.com/each/ "We can stop the loop from within the callback function by returning false."
The function can return false
.
edit oh ha ha, the "from foo" was scrolled off the right side :)
To do that, you could use try/catch
function foo() {
try {
jQuery('whatever').each(function() {
if (noMoreFoo()) throw "go";
});
}
catch (flag) {
if (flag === "go") return;
throw flag;
}
}
Not really. This will ghetto do what you want (i think):
function foo() {
var bar=null;
$(whatever).each( function() {
bar="bar";
return false;
});
return bar;
}
var fooResults = foo();
function foo() {
$result = false;
jQuery(whatever).each( function() {
$result = true;
});
// We will reach this point after the loop is over.
return $result;
}
精彩评论