jquery - 如何从每个语句中退出(中断函数)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5515109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery - how to exit (break function) from each statement?
提问by joshua
for example I use following code:
例如我使用以下代码:
$("img").each(function(i){
x += $("img:eq(" + i ")").width();
if(some conditional) return;
});
after return I would like to not adding anything to x, how could I achieve it?
返回后我不想向 x 添加任何内容,我该如何实现?
回答by Andy McCluggage
From the JQuery doco...
从JQuery 文档...
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.
我们可以通过使回调函数返回 false 来在特定迭代中中断 $.each() 循环。返回非 false 与 for 循环中的 continue 语句相同;它将立即跳到下一次迭代。
So essentially this means...
所以基本上这意味着......
return false;
= break;
return false;
= break;
return true;
or return;
= continue;
return true;
或return;
=continue;
回答by Matthew Flaschen
You can return false
to cause each
to stop calling the function. However, a regular loop and a break statement might be clearer.
您可以return false
导致each
停止调用该函数。但是,常规循环和 break 语句可能更清晰。