开发者

jQuery alternative to $.each

开发者 https://www.devze.com 2023-02-27 10:11 出处:网络
I found that the $.each is very slow and makes problems to the web pages if containing lot of various jQuery effects.

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() {开发者_StackOverflow
   var singleLi = $(this);
});

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

Thanks.


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.


Exactly the same way without each

$('#list li').hover(function() {
        $('#myDiv').stop().fadeIn(400);
    }, function() {
        $('#myDiv').stop().fadeOut(400);
    })
});


yes... just add the hover to all li's

$('#list li').hover(function() {
    $('#myDiv').fadeIn(400);
}, function() {
    $('#myDiv').fadeOut(400);
});

$('#myDiv').fadeOut(400);


As an ID has to be unique, that whole script should not alter if the .each() is removed.

$.hover() does not mean much.

$('#list li').hover(function() {
    $('#myDiv').fadeIn(400);
}, function() {
    $('#myDiv').fadeOut(400);
});

$('#myDiv').fadeOut(400);
0

精彩评论

暂无评论...
验证码 换一张
取 消