How to break/exit from a each() function in JQuery?
本问题已经有最佳答案,请猛点这里访问。
我有一些代码:
1 2 3 4 | $(xml).find("strengths").each(function() { //Code //How can i escape from this block based on a condition. }); |
如何根据条件从"每个"代码块中逃脱?
更新:如果我们有这样的东西怎么办:
1 2 3 4 5 | $(xml).find("strengths").each(function() { $(this).each(function() { //I want to break out from both each loops at the same time. }); }); |
是否可以从内部的"每个"功能中分离出两个"每个"功能?
19.03.2013
如果你想继续而不是爆发
1 | return true; |
根据文档,您可以简单地使用cx1〔0〕来中断:
1 2 3 4 5 | $(xml).find("strengths").each(function() { if (iWantToBreak) return false; }); |
从匿名函数返回false:
1 2 3 4 5 | $(xml).find("strengths").each(function() { // Code // To escape from this block based on a condition: if (something) return false; }); |
从每个方法的文档中:
Returning 'false' from within the each
function completely stops the loop
through all of the elements (this is
like using a 'break' with a normal
loop). Returning 'true' from within
the loop skips to the next iteration
(this is like using a 'continue' with
a normal loop).
您可以使用
1 2 3 4 5 6 7 8 | +----------------------------------------+ | JavaScript | PHP | +-------------------------+--------------+ | | | | return false; | break; | | | | | return true; or return; | continue; | +-------------------------+--------------+ |
1 2 3 | if (condition){ // where condition evaluates to true return false } |
见3天前提出的类似问题。