Reputation: 26006
I have this code, where I would like that next
skips to next iteration.
$.each(result, function(key, value) {
if (value.type == "individuel") {
cform["IN"] = "checked";
} else if (value.type == "course") {
cform["CO"] = "checked";
} else {
next;
}
cform["ID"] = key;
cform["title"] = value.title;
$('#template').tmpl(cform).appendTo('#content');
});
But next
apparently means something different from what I would expect.
It seams to me that next
exits the $.each
rather than skipping the current key/value.
Does there exist a way to do next
like I would expect?
Upvotes: 1
Views: 1857
Reputation: 4160
Use continue;
to skip to the next iteration in a loop.
Edit: Yep, sorry about that I swear I saw a loop in there :( You can "continue" in jQuery's each() by returning a non-false value, will a return work for your case?
Upvotes: -1
Reputation: 338316
Due to the nature of jQuery, there is no way to state a "next" in the function body. The inner function does not know that it is being executed in a loop and can therefore not influence this fact.
But you can return early, which has the same effect:
$.each(result, function(key, value) {
if (value.type == "individuel") {
cform["IN"] = "checked";
} else if (value.type == "course") {
cform["CO"] = "checked";
} else {
return true;
}
cform["ID"] = key;
cform["title"] = value.title;
$('#template').tmpl(cform).appendTo('#content');
});
I find this more stylish:
$.each(result, function(key, value) {
switch (value.type) {
case "individuel": cform["IN"] = "checked"; break;
case "course": cform["CO"] = "checked"; break;
default: return true;
}
cform["ID"] = key;
cform["title"] = value.title;
$('#template').tmpl(cform).appendTo('#content');
});
Upvotes: 7
Reputation: 237975
Unlike other constructs, such as for..in
and while
, $.each
is not a language construct. With those constructs, you can use continue
to skip the current element and break
to leave the loop. Since $.each
takes a callback function, you need to use the callback's return
value to affect what happens next.
Return true
to continue to the next item; return false
to break the loop.
In this case, you should use return true
:
else {
return true; // skip to next element
}
Upvotes: 6
Reputation: 2046
return true;
From the docs:
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.
Upvotes: 3
Reputation: 103145
Using the if statement makes the next unnecessary. Simply do whatever you want in the if and ignore the else. The iteration moves on automatically.
Upvotes: 1