最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to update a jQuery object stored in a variable after DOM change? - Stack Overflow

programmeradmin0浏览0评论

I normally store my jQuery objects in variables to avoid having the selector written all over the place.

When I change the DOM, I would like to make the object update itself. Dropping unused references and getting updated with the new ones. How can I do this? Ideally I want to do something with the following logic:

var test = $('div.bar');
console.log(test);
>> [<div class="bar" id="b1"></div>, <div class="bar" id="b2"></div>]

$('#b2').remove();
console.log(test);
>> [<div class="bar" id="b1"></div>, <div class="bar" id="b2"></div>]

test.update();
console.log(test);
>> [<div class="bar" id="b1"></div>]

$('body').append('<div class="bar" id="b3"></div>');
console.log(test);
>> [<div class="bar" id="b1"></div>]

test.update();
console.log(test);
>> [<div class="bar" id="b1"></div>, <div class="bar" id="b3"></div>]

I normally store my jQuery objects in variables to avoid having the selector written all over the place.

When I change the DOM, I would like to make the object update itself. Dropping unused references and getting updated with the new ones. How can I do this? Ideally I want to do something with the following logic:

var test = $('div.bar');
console.log(test);
>> [<div class="bar" id="b1"></div>, <div class="bar" id="b2"></div>]

$('#b2').remove();
console.log(test);
>> [<div class="bar" id="b1"></div>, <div class="bar" id="b2"></div>]

test.update();
console.log(test);
>> [<div class="bar" id="b1"></div>]

$('body').append('<div class="bar" id="b3"></div>');
console.log(test);
>> [<div class="bar" id="b1"></div>]

test.update();
console.log(test);
>> [<div class="bar" id="b1"></div>, <div class="bar" id="b3"></div>]
Share Improve this question asked Dec 30, 2012 at 11:54 fmsffmsf 37.2k49 gold badges153 silver badges196 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 7

This plugin solves that problem:

(function ( $ ) {
  $.fn.update = function(){
    var newElements = $(this.selector),i;    
    for(i=0;i<newElements.length;i++){
      this[i] = newElements[i];
    }
    for(;i<this.length;i++){
      this[i] = undefined;
    }
    this.length = newElements.length;
    return this;
  };
})(jQuery);

Just add it to your code and do:

var $foo = $("div.bar"); // selects all "div.bar"
(... many dom modifications ...)
$foo.update();
发布评论

评论列表(0)

  1. 暂无评论