jQuery持久性非事件绑定

时间:2012-05-24 17:29:24

标签: javascript jquery

 var $thingy = $('.thingy'),
     $window = $(window);

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

是否可以向页面添加更多.thingy并在不重新查询的情况下调整大小?

我知道以下内容可行:

 var $window = $(window);

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

问题是,我不是经常向页面添加.thingy,这使得创建新的jQuery对象和快速重新查询DOM看起来像很多开销。

有更好的方法吗?

2 个答案:

答案 0 :(得分:2)

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

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


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

答案 1 :(得分:1)

每当您添加新的.thingy时,请使用

更新选择
$thingy = $('.thingy');

$thingy = $thingy.add(the_new_thingy)

当然,$thingy必须在两个地方都可见。