我有一些代码:

$(xml).find("strengths").each(function() {
   //Code
   //How can i escape from this block based on a condition.
});

我如何从“每个”基于条件的代码块逃脱?

更新:

如果我们有这样的东西:

$(xml).find("strengths").each(function() {
   $(this).each(function() {
       //I want to break out from both each loops at the same time.
   });
});

有没有可能从内部的“每个”函数中跳出两个“每个”函数?

# 19.03.2013

如果你想继续而不是爆发

return true;

根据文档,你可以简单地返回false;打破:

$(xml).find("strengths").each(function() {

    if (iWantToBreak)
        return false;
});

从匿名函数返回false:

$(xml).find("strengths").each(function() {
  // Code
  // To escape from this block based on a condition:
  if (something) return false;
});

从每个方法的文档中:

从each中返回'false' 函数完全停止循环 通过所有的元素(这是 比如在normal后面加break 循环)。从内部返回“true” 循环跳转到下一个迭代 (这就像使用“continue”with 一个正常的循环)。


if (condition){ // where condition evaluates to true 
    return false
}

见3天前问的类似问题。


你可以使用return false;

+----------------------------------------+
| JavaScript              | PHP          |
+-------------------------+--------------+
|                         |              |
| return false;           | break;       |
|                         |              |
| return true; or return; | continue;    |
+-------------------------+--------------+