首页 文章

如何在JQuery中打破/退出each()函数? [重复]

提问于
浏览
556

这个问题在这里已有答案:

我有一些代码:

$(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

If you want to continue instead of break out

return true;

4 回答

  • 22

    根据documentation你可以简单地 return false; 来打破:

    $(xml).find("strengths").each(function() {
    
        if (iWantToBreak)
            return false;
    });
    
  • 103

    从匿名函数返回false:

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

    each method的文档:

    从每个函数中返回'false'完全停止循环遍历所有元素(这就像使用带有正常循环的'break') . 从循环内返回'true'会跳到下一次迭代(这就像使用带有正常循环的'continue') .

  • 937

    你可以用 return false;

    +----------------------------------------+
    | JavaScript              | PHP          |
    +-------------------------+--------------+
    |                         |              |
    | return false;           | break;       |
    |                         |              |
    | return true; or return; | continue;    |
    +-------------------------+--------------+
    
  • 98
    if (condition){ // where condition evaluates to true 
        return false
    }
    

    请参阅similar question 3天前询问 .

相关问题