代码之家  ›  专栏  ›  技术社区  ›  Orson

如何在jquery中中断/退出each()函数?[复制品]

  •  565
  • Orson  · 技术社区  · 15 年前

    这个问题已经有了答案:

    我有一些代码:

    $(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;
    
    4 回复  |  直到 9 年前
        1
  •  955
  •   Greg    15 年前

    根据 documentation 你可以简单 return false; 要断开:

    $(xml).find("strengths").each(function() {
    
        if (iWantToBreak)
            return false;
    });
    
        2
  •  103
  •   RRikesh    12 年前

    从匿名函数返回false:

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

    each method :

    从每个内部返回“false” 函数完全停止循环 通过所有元素(这是 就像在正常情况下使用“休息” 循环)。从内部返回“true” 循环跳到下一个迭代 (这就像用“continue”来 正常循环)。

        3
  •  100
  •   aksu    11 年前

    你可以使用 return false;

    +----------------------------------------+
    | JavaScript              | PHP          |
    +-------------------------+--------------+
    |                         |              |
    | return false;           | break;       |
    |                         |              |
    | return true; or return; | continue;    |
    +-------------------------+--------------+
    
        4
  •  22
  •   Community CDub    8 年前
    if (condition){ // where condition evaluates to true 
        return false
    }
    

    看见 similar question 三天前问的。