开发者

jQuery Collection Cache

开发者 https://www.devze.com 2023-01-21 15:21 出处:网络
Does anyone know a good way to cache a collection of objects returned by a selector. var $platforms = $(\".platforms\");

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

精彩评论

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