简体   繁体   English

jQuery:如何突破each()及其内部的功能?

[英]Jquery: How to break out of each() and the function it's inside in?

$("#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")
});

Just having a bit of trouble with this one. 对此有一点麻烦。 I want to exit the jquery each loop AND click function altogether. 我想退出jquery每个循环并完全单击功能。 But 'return' just takes me out of the each loop only. 但是“返回”只是让我退出了每个循环。 How do I completely exit the click function altogether? 如何完全退出点击功能?

If there is nothing in the table, the each function will actually never be executed (since the collection being iterated over is empty). 如果表中没有任何内容,则each函数实际上将永远不会执行 (因为要迭代的集合为空)。

Perhaps you meant to put the condition as the first line in your click function: 也许您打算将条件作为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")
});

As a side note, if the each function is the only thing in this block, you do not need to do anything special for the empty-table case, since the each function will simply be executed zero times. 附带说明一下,如果each功能都是该块中的唯一内容,则无需为空表情况做任何特殊的事情,因为每个功能将简单地执行零次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM