8

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'm using an .each() iteration to collect values. I thought it functioned like a loop so i thought id use a break statement to break out. This is throwing an "illegal" error. Does anyone know how to break out of an each iteration?

Community
  • 1
  • 1
dopatraman
  • 13,416
  • 29
  • 90
  • 154

4 Answers4

14

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

gtr32x
  • 2,033
  • 4
  • 20
  • 32
4

To break out of .each(), simply use return false;

Take a look at the jQuery .each() docs for more information.

Here's an example, given in the docs:

$("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;
        }
    });
});​
James Hill
  • 60,353
  • 20
  • 145
  • 161
1

its a function, you can just return false to break out of the loop altogether or, if you want something that works like the continue statement, you can return true

each( function() 
{
   if ( someCondition ) return true; // same as continue;
   if ( someOtherCondition) return false; // same as break;
} );
Muad'Dib
  • 28,542
  • 5
  • 55
  • 68
0

You're not really in a for-each loop, so a break doesn't make sense. It's actually a function that is being called each time, so you need to return from that function and tell jQuery to stop calling.

Return false instead, and that should break out of the loop.

Mike Mooney
  • 11,729
  • 3
  • 36
  • 42