function outer() {
$(['hi', 'there']).each(function(idx, e) {
console.log(e);
return;
});
alert("I don't want to be called");
}
function outer() {
$.get('http://test.com', function (data) {
console.log(data)
return; // I want to terminate the entire outer() function here.
});
alert("I don't want to be called");
}
在这种情况下,打破嵌套函数的惯例是什么?当使用 for
循环时,在它们内部返回会终止包含它们的整个函数。但是,由于 $.each()
是一个单独的函数调用,因此从它返回只会结束自身,而不是外部函数。我可以简单地 return
两次,一次在里面,一次在外面,但我不确定我将如何处理 $.ajax()
因为有必要终止仅当我获得成功响应时才执行此功能。
最佳答案
这里总结了它的工作原理。
.each()
return true; // skips to the next iteration of .each()
return false; // exits the .each() loop
简而言之,无法在单个语句中突破包含 .each()
的函数。
$.get()
return [true|false]; // makes no sense at all.
由于 $.get()
中的返回在 ajax 调用完成之前不会被执行,因此它没有多大用处。即使当您进行同步 ajax 调用时,成功回调中的 return 语句仍然没有做任何实质性的事情。 将函数的返回视为分配给调用语句的值。
是什么让您有必要打破您的功能?
关于javascript - 从嵌套函数返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23771929/