How to exit .each () iteration

Possible duplicate:
Nested jQuery.each () - continue / break

Here is my code:

var steps = $("div#f");
steps.each(function () {
    var s = $(this);
    var cs = $(this).find(".Cm");
    cs.each(function () {
        var tc = $(this);
        var err = tc.attr("h");
        if (err == false) {
            this.c = err;//this.c is a global variable
            return this.c;
            break;//here is where the error is being thrown
        }
        else {
            this.c =  {"Eval": err, "S": s, "Cm": tc};
            return this.c;
        }
    });
});

I use iteration .each()to collect values. I thought this worked like a loop, so I thought id was using an instruction break. This causes an “illegal” error. Does anyone know how to get out of the iteration each?

+5
source share
4 answers

use return false. Take a look at this resource: http://gavinroy.com/jquery-tip-how-to-break-out-of-each

+10
source

To exit .each(), just usereturn false;

See jQuery .each()docs for more information.

, :

$("button").click(function() {
    $("div").each(function(index, domEle) {
        // domEle == this
        $(domEle).css("backgroundColor", "yellow");
        if ($(this).is("#stop")) {
            $("span").text("Stopped at div index #" + index);
            return false; //Equivalent to break;
        }
    });
});​
+3

, . , , jQuery .

false, .

0
source

its function, you can just return falseto breakget out of the loop at all, or if you want something that works as an operator continue, you canreturn true

each( function() 
{
   if ( someCondition ) return true; // same as continue;
   if ( someOtherCondition) return false; // same as break;
} );
0
source

All Articles