简体   繁体   中英

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 carousel 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?

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);

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM