i have the following code:
$.each(data.People, function (i, person) {
html.push("<img title='" + person.Name + "' height='45' width='45' src='" + person.Picture + "' /> ");
});
I want to change this code so if the the array (data.People) has more than 20 people, it will do what its doing above for the first 20 people and then just show text saying "X" more people... so for example if the array had 100 people it would show the first 20 and then just say "80 more people . . ."
I am assuming i need some counter inside the each statement but wanted to see the best way to break out of that and show the remaining text.
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.
There is no way to stop or break a forEach() loop other than by throwing an exception.
jQuery stop() Method The stop() method stops the currently running animation for the selected elements.
The each() method specifies a function to run for each matched element. Tip: return false can be used to stop the loop early.
return false
breaks from each
loop in jQuery, just like break
in for
loop in plain JavaScript.
And return true
is like continue
.
For the X
part you would need to get the length
of the collection being iterated since each
doesn't provide that info, unfortunately.
So, in your case:
$.each(data.People, function (i, person) {
if (i == 20) {
html.push("<p>" + (data.People.length - i) + " more people...</p>");
return false;
}
html.push("<img title='" + person.Name + "' height='45' width='45' src='" + person.Picture + "' /> ");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With