jQuery update variable referencing DOM elements
I have 2 variables set like this:
var carousel = $('div.carousel ul');
var pics = carousel.children('li');
Later on a few new <li>
get added to the carou开发者_运维技巧sel using insertBefore()
however my pics
variable is now out of date so I have to call pics = carousel.children('li');
again in my function.
Is there a better way of doing this without repeated traversing of the DOM?
jQuery has an add()
function which will take an argument and add that to the list of selected items. You can call pics.add(newli);
any time you add a new list item to the DOM.
I like to store jQuery objects to avoid having selectors all over the place. So I created a micro plugin to extend jQuery objects with an update
function. You can find the gist here
Here is the code for reference:
(function ( $ ) {
$.fn.update = function(){
var newElements = $(this.selector),i, oldLength = this.length;
this.length = newElements.length;
for(i=0;i<this.length;i++){
this[i] = newElements[i];
}
for(;i<oldLength;i++){
this[i] = undefined;
}
return this;
};
})(jQuery);
Why is pics = carousel.children('li');
so time consuming?
It seem okay to do that again if the list had changed, but if you are really sure you want to avoid it, try adding the 2 new created li
into a new array and then add pics to it.
精彩评论