Is it possible to run a jQuery .each statement a certain amount of times rather then for each of the items being iterated? The JSON being iterated is a last.fm feed, and of course, they ignore the "limit" request often. I would like to bypass this error by only running the .each statement so many times.
A:
Return false
out of the iterator when you want to stop. The first parameter to your iterator is the index (when looping through arrays).
T.J. Crowder
2010-01-21 19:33:03
Um...? What's with the markdown? The answer is direct, straightforward, correct, and links to further information. Yeesh.
T.J. Crowder
2010-01-22 15:08:06
+4
A:
var limit = 5;
$("somelement").each(function(i, val) {
if(i > limit) return false;
// do stuff
});
or
$("somelement:lt(5)").each(function() {
// do stuff
});
Balon
2010-01-21 19:32:57
This seems like strong-armed a solution when one already exists in jQuery.
ashchristopher
2010-01-21 19:35:46
Actually this works - I was just off by one with the JSON item count. thanks.
Kyle
2010-01-21 19:50:51
+7
A:
Rather than modify the .each, modify your selector to select only the first 'n' elements.
ashchristopher
2010-01-21 19:33:59
A:
Define a variable before your loop, increment it within the each, and if(myvar == 10){return false;}
Returning 'false' from within the each function completely stops the loop http://docs.jquery.com/Core/each
neatlysliced
2010-01-21 19:35:21
Ooh I like the second option of Balon's answer.. I didn't know you could do that!
neatlysliced
2010-01-21 19:36:14
I disagree with the markdown, because you could be checking for other things - he may not have been looking for a certain element, it could have involved other logic, which my answer was still a viable solution.
neatlysliced
2010-01-21 20:58:24