tags:

views:

117

answers:

4

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
Um...? What's with the markdown? The answer is direct, straightforward, correct, and links to further information. Yeesh.
T.J. Crowder
+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
@Lance He does return false.
Josh Stodola
This seems like strong-armed a solution when one already exists in jQuery.
ashchristopher
Would this work on JSON data? That's what's being changed.
Kyle
http://docs.jquery.com/Ajax/jQuery.getJSON#demo
Nagyman
Actually this works - I was just off by one with the JSON item count. thanks.
Kyle
+7  A: 

Rather than modify the .each, modify your selector to select only the first 'n' elements.

http://docs.jquery.com/Selectors/lt#index

ashchristopher
$("somelement:lt(5)"); will pull back 5 elements
Jeremy
+1: This seems like the best way to do it.
R. Bemrose
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
Ooh I like the second option of Balon's answer.. I didn't know you could do that!
neatlysliced
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