开发者

jQuery alternative to $.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() {开发者_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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜