Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to break out of a .each() jquery statement?

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.

like image 447
leora Avatar asked Dec 29 '11 18:12

leora


People also ask

How can I break exit from a each () function in jQuery?

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.

How do you break for each loop?

There is no way to stop or break a forEach() loop other than by throwing an exception.

How do you stop a function call in jQuery?

jQuery stop() Method The stop() method stops the currently running animation for the selected elements.

What is each in jQuery?

The each() method specifies a function to run for each matched element. Tip: return false can be used to stop the loop early.


1 Answers

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 + "' /> ");
});
like image 81
Oleg Mikheev Avatar answered Nov 03 '22 12:11

Oleg Mikheev