开发者

jQuery Collection Cache

Does anyone know a good way to cache a collection of objects returned by a selector.

var $platforms = $(".platforms");    
var i = 0, l = $platforms.length, current;

for(;i<l;i++) {
    current = $($platforms[i]); //calling jQuery() in a loop. Should be cached
}

The above code creates 开发者_StackOverflowa jQuery instance of each element returned by $(".platform") when it should be cached. Is there any easy way to do this?


To literally get an array of jQuery wrappers of elements, you can use .map() like this:

var $platforms = $(".platforms").map(function() { return $(this); }).get();

Then in your for loop $platforms[i] will be a jQuery object.


It depends what you're after though, there's .each() like this:

$(".platforms").each(function(i,elem) {
  var current = $(this);
});

Or use .eq() to get a jQuery wrapped element at that index in your loop, like this:

for(;i<l;i++) {
  current = $platforms.eq(1);
}

It all depends on what you're after....why are you looping through the elements? Most jQuery operations operate on sets, not individual elements, so for example $(".platforms").bind(...) would bind to all of the elements that selector found.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜