Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery alternative to $.each

Tags:

jquery

each

I found that the $.each is very slow and makes problems to the web pages if containing lot of various jQuery effects.

I'd like to know if there is a good alternative to the $.each, for example:

$('ul li').each(function() {
   var singleLi = $(this);
});

without the hover, how can I do the same without using each?

Thanks.

like image 582
Andrea Turri Avatar asked Apr 21 '11 15:04

Andrea Turri


1 Answers

If you want an actual alternative to "$.each()", just use a "for" loop:

var liElements = $('ul li');
for (var i = 0; i < liElements.length; ++i) {
  var li = liElements[i];
  // ... lots of various jQuery effects ...
}

The suggestions that you can skip ".each()" and just use ".hover()" directly are correct, but they miss the point: those jQuery routines will perform a ".each()" internally anyway.

I doubt that switching from "$.each()" to the "for" loop will all by itself make much of a difference, however.

like image 171
Pointy Avatar answered Oct 21 '22 21:10

Pointy