Reputation: 11112
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.
Upvotes: 7
Views: 6538
Reputation: 11207
The best solution is to use the .slice method in jQuery.
var limit = 5;
$("somelement").slice(0, limit).each(function(i, val) {
// do stuff
});
Upvotes: 4
Reputation: 245
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
Upvotes: 2
Reputation: 26271
Rather than modify the .each, modify your selector to select only the first 'n' elements.
http://docs.jquery.com/Selectors/lt#index
Upvotes: 11
Reputation: 1074495
Return false
out of the iterator when you want to stop. The first parameter to your iterator is the index (when looping through arrays).
Upvotes: 1
Reputation: 8410
var limit = 5;
$("somelement").each(function(i, val) {
if(i > limit) return false;
// do stuff
});
or
$("somelement:lt(5)").each(function() {
// do stuff
});
Upvotes: 19