本文翻译自:How to break/exit from a each() function in JQuery? [duplicate]
This question already has an answer here: 这个问题已经在这里有了答案:
- How to break out of jQuery each Loop 6 answers 如何打破jQuery每个循环的 6个答案
I have some code: 我有一些代码:
$(xml).find("strengths").each(function() {
//Code
//How can i escape from this block based on a condition.
});
How can i escape from the "each" code block based on a condition? 如何根据条件从“每个”代码块中退出?
Update: 更新:
What if we have something like this: 如果我们有这样的事情怎么办:
$(xml).find("strengths").each(function() {
$(this).each(function() {
//I want to break out from both each loops at the same time.
});
});
Is it possible to break out from both "each" functions from the inner "each" function? 是否有可能从内部的“每个”功能中同时脱离这两个“每个”功能?
# 19.03.2013 #19.03.2013
If you want to continue instead of break out 如果您想继续而不是爆发
return true;
#1楼
参考:https://stackoom.com/question/7Y4i/如何从JQuery中的each-函数中断-退出-重复
#2楼
You can use return false;
您可以使用return false;
+----------------------------------------+
| JavaScript | PHP |
+-------------------------+--------------+
| | |
| return false; | break; |
| | |
| return true; or return; | continue; |
+-------------------------+--------------+
#3楼
According to the documentation you can simply return false;
根据文档,您可以简单地return false;
to break: 打破:
$(xml).find("strengths").each(function() {
if (iWantToBreak)
return false;
});
#4楼
Return false from the anonymous function: 从匿名函数返回false:
$(xml).find("strengths").each(function() {
// Code
// To escape from this block based on a condition:
if (something) return false;
});
From the documentation of the each method : 从每种方法的文档中:
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). 从每个函数中返回“ false”将完全停止所有元素的循环(这就像在正常循环中使用“ break”一样)。 Returning 'true' from within the loop skips to the next iteration (this is like using a 'continue' with a normal loop). 从循环内返回“ true”会跳到下一个迭代(这就像对正常循环使用“ continue”一样)。
#5楼
if (condition){ // where condition evaluates to true
return false
}
see similar question asked 3 days ago. 看到3天前问的类似问题 。