2012-05-24 44 views
0
var $thingy = $('.thingy'), 
    $window = $(window); 

$window.on('resize', function(){ 
     thingy.width($window.width()/12); 
}); 

是否有可能更.thingy s添加到页面,让他们调整而无需重新查询?jQuery的持续性非事件绑定

我知道下面的工作:

var $window = $(window); 

$window.on('resize', function(){ 
     $('.thingy').width($window.width()/12); 
});  

的问题是,我不加入.thingy s到的页面,很多时候,作出新的jQuery对象和快速重新查询的创建DOM似乎有很多开销。

有没有更好的方法?

回答

1

无论何时您

$thingy = $('.thingy'); 

$thingy = $thingy.add(the_new_thingy) 

当然$thingy添加一个新的.thingy,更新的选择必须是在两个地方可见。

+0

按照[文档](http://api.jquery.com/add/),“*的。新增()方法构造一个新的jQuery对象*“。然而,这也是我的第一个想法...... – Bergi

+0

太糟糕的jQuery似乎不支持追加到现有的对象。它使得一个jQuery对象作为一个引用类型不太可用。 – 2012-05-24 17:47:42

+0

这还意味着我不必为每个resize事件重新构造 - 重新查询,它允许我根据需要添加和重新构建。 – Fresheyeball

2

可以简单地重新分配给变量:

var $window = $(window), 
    $thingy = $('.thingy'); 
$window.on('resize', function(){ 
    $thingy.width($window.width()/12); 
}); 


// then sometime: 
$thingy = $('.thingy'); 
// or: 
$thingy = $thingy.add(elements)