【问题标题】:Jquery: How to break out of each() and the function it's inside in?Jquery:如何打破 each() 和它在里面的函数?
【发布时间】:2013-12-30 06:24:06
【问题描述】:
$("#savebtn").click(function() {

    $('.mytable tr').each(function(){
      if($('.mytable tr').length < 1){
          alert("Nothing in the table!")
          return 
      }
    });
alert("You are still inside the click function")
});

只是在这方面有点麻烦。我想完全退出 jquery 每个循环并单击功能。但是“返回”只是让我脱离了每个循环。如何彻底退出点击功能?

【问题讨论】:

  • $('.mytable tr').length &lt; 1 inside .each 循环使用相同的选择器永远不会发生。顺便说一句,您可以在每个循环中使用 return false 来摆脱它。你到底想做什么?
  • return 仍然让​​我留在函数中,我也想在每个循环内的 if 语句中跳出函数
  • 这不是指定问题的重复。需要知道如何打破 each() 和函数。
  • 我唯一能想到的就是将一个标志标记为真,突破每个标志,然后检查标志并再次返回。看起来很乱。

标签: jquery function loops return each


【解决方案1】:

如果表中没有任何内容,each 函数实际上将永远不会被执行(因为被迭代的集合是空的)。

也许您的意思是把条件作为click 函数的第一行:

$("#savebtn").click(function() {
    if($('.mytable tr').length < 1) {
        alert("Nothing in the table!");
        return;
    }

    $('.mytable tr').each(function() {
        doSomething(this);
    });

    alert("You are still inside the click function")
});

附带说明,如果 each 函数是此块中的唯一内容,则无需针对空表情况执行任何特殊操作,因为每个函数将简单地执行零次。

【讨论】:

  • 这很好,谢谢,最好把 if 语句放在函数的顶部,而不是在每个循环中。
  • 这并没有回答打破每个和功能的原始问题。哦,好吧,也许重复的问答会。 - 不,它没有。
猜你喜欢
  • 2012-10-24
  • 1970-01-01
  • 2012-02-05
  • 1970-01-01
  • 2012-02-27
  • 2012-09-10
  • 2011-04-26
  • 2023-04-04
  • 1970-01-01
相关资源
最近更新 更多