How do I break out of an $.each in jquery?

后端 未结 6 1281
抹茶落季
抹茶落季 2020-12-18 14:45

How to I break out of the following jquery each method when a condition is met;

var rainbow = {\'first\' : \'red\', \'second\' : \'orange\',         


        
相关标签:
6条回答
  • 2020-12-18 15:08

    We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

    0 讨论(0)
  • 2020-12-18 15:08

    We can not use Break and Continue in jquery functions
    Try this

    var rainbow = {'first' : 'red', 'second' : 'orange', 'third' : 'yellow'};
    
    $.each(rainbow, function (key, color) {
    
      if (color == 'red') {
        //do something and then break out of the each method
        alert("i'm read, now break.");
        return false;
      }
      alert(color);
    });
    
    0 讨论(0)
  • 2020-12-18 15:11

    As explicitly written on jQuery's page for $.each :

    We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

    Please google the terms you search before posting here ! It's a pity that jQuery has one of the best documentations ever if you do not bother to read about it !

    0 讨论(0)
  • 2020-12-18 15:17

    The JQuery documentation for each states:

    We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

    It also provides examples.

    0 讨论(0)
  • 2020-12-18 15:26
    var rainbow = {'first' : 'red', 'second' : 'orange', 'third' : 'yellow'};
    
    $.each(rainbow, function (key, color) {
    
      if (color == 'red') {
    
        //do something and then break out of the each method
        alert("i'm read, now break.");
    
        return false;
    
      }
    
    });
    
    0 讨论(0)
  • 2020-12-18 15:31
    <script>
        var arr = [ "one", "two", "three", "four", "five" ];
    
        jQuery.each(arr, function() {
          $("#" + this).text("Mine is " + this + ".");
           return (this != "three"); // will stop running after "three"
       });
    
    
    </script>
    

    Try this

    http://api.jquery.com/jQuery.each/

    0 讨论(0)
提交回复
热议问题