如何在DOM更改后更新存储在变量中的jQuery对象
How to update a jQuery object stored in a variable after DOM change?
我通常将jQuery对象存储在变量中,以避免到处都写选择器。
当我改变DOM时,我想让对象更新自己。删除未使用的引用并使用新的引用进行更新。我该怎么做呢?理想情况下,我想用以下逻辑做一些事情:
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>]
这个插件解决了这个问题:
(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);
只需将其添加到您的代码中并执行:
var $foo = $("div.bar"); // selects all "div.bar"
(... many dom modifications ...)
$foo.update();
相关文章:
- 值未传递给变量(JQuery、Javascript)
- 附加要使用的变量jQuery验证插件
- 按钮变量范围 - 如何更新父范围中的变量?jQuery.
- grunt-contrib-jasmine ReferenceError: 找不到变量: jQuery.
- 未定义的变量 jQuery 对象
- 调用变量 jQuery 函数
- 访问正在改变函数内部的变量(jQuery)
- 在变量jquery日期选择器中获取今天的日期和所选日期
- 如何序列化存储在变量 jQuery 中的表单
- 如何在单独的函数中获取此变量?(jQuery)
- 可以't在嵌套函数中使用javascript变量(jquery砖石插件)
- 将.attr()添加到变量Jquery中
- 将.change函数中变量的值传递并更新到全局变量Jquery
- 将ajax变量Jquery到php中
- 用两个双引号和加号包围javascript变量jquery $.post
- 如何将html结构存储在变量jquery中
- 如何通过名称空间变量进入点击函数参数变量?jQuery
- 检查if条件,if语句被赋值为字符串变量- jquery|| javascript
- 从on()函数返回变量- jquery
- 创建一个变量,在每个循环中使用一个变量- jQuery