简体   繁体   中英

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. 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).

Perhaps you meant to put the condition as the first line in your click function:

$("#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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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