返回例如:的Javascript/JQuery的:立即PARENT函数在调用每个()通过匿名功能
> function foo() {
> jQuery(whatever).each(function() {
return; // this just exits the anonymous function - is there a way to return from foo?
}
);
>
> }
返回例如:的Javascript/JQuery的:立即PARENT函数在调用每个()通过匿名功能
> function foo() {
> jQuery(whatever).each(function() {
return; // this just exits the anonymous function - is there a way to return from foo?
}
);
>
> }
**更正:添加更多详情。使用一个标志,允许从父函数返回**
function foo() {
var doreturn = false;
jQuery(whatever).each(function() {
if(youwanttoreturn){
doreturn=1;
return false;
}
});
if(doreturn)return;
}
http://api.jquery.com/each/ “我们可以通过返回false从回调函数中停止循环。”
该函数可以返回false
。
编辑哦哈哈, “从富” 被滚出右侧:)
要做到这一点,你可以使用try/catch语句
function foo() {
try {
jQuery('whatever').each(function() {
if (noMoreFoo()) throw "go";
});
}
catch (flag) {
if (flag === "go") return;
throw flag;
}
}
它稍快使用一个变量来检查是否必须比使用try/catch语句返回。看看我这个jsPerf:http://jsperf.com/returning-a-parent-function-from-inside-a-child – 2012-08-02 20:03:46
不是。这将贫民窟做你想做的(我认为):
function foo() {
var bar=null;
$(whatever).each(function() {
bar="bar";
return false;
});
return bar;
}
var fooResults = foo();
+1为“贫民窟做” – iamwhitebox 2014-01-22 00:17:14
function foo() {
$result = false;
jQuery(whatever).each(function() {
$result = true;
});
// We will reach this point after the loop is over.
return $result;
}
?? ??我不认为这会做任何事情;就像jQuery一样,它就像'return'一样没有价值。 – Pointy 2010-04-08 17:17:37
@Pointy谢谢,更正。 – 2010-04-08 17:20:30
他想从“foo”回来! – Pointy 2010-04-08 17:18:48
使用变量+1。它比使用try/catch稍快。看看我这个jsPerf:http://jsperf.com/returning-a-parent-function-from-inside-a-child – 2012-08-02 20:03:26