2

我正在运行这个:

$("*:not(#boo) .content").livequery(function(){  
  $("input, select").blah();
});

blah()看起来像这样:

(function( $ ) {
  $.fn.blah = function(){
    var that = this;
    return this.each(function(){
       $(this).bind('change', function(){
           // do some stuff here

           return true;
        }).change();

   });
 };

})(jQuery);

html看起来像:

<div id="boo">
 <div class="content">
  <input type="text" />
  <input type="text" />
  ...
 </div>
</div>

<div class="content">    
 <input type="text" />
 <input type="text" />
</div>
...

所以我要做的是将该函数和事件附加到不在内部的每个输入元素上#boo。这行得通,但问题是它像每秒一样一遍又一遍地进行,并且浏览器冻结了。

我需要 livequery,因为 html 有时会更新,我需要再次将事件附加到新元素。

那么如何检查是否blah()已经应用于输入元素并停在那里?

4

2 回答 2

2

老实说,我不会那样做。您的第一条语句是一个很大的 NoNo,通过查询标记中的每个节点,然后排除您需要的元素。为什么不这样做:

$('input').filter(function() { return !!$(this).closest('#boo').length } )
          .live('change', function() {
              // do some stuff here
          }).change();

这当然只有在没有超出我范围的事情要做的情况下才有意义。但看起来你甚至不需要.livequery这里。

更新

上面的代码无法工作。但这应该这样做:

$('input').live('change', function() {
    if(!$(this).closest('#boo').length) {
        // do some stuff here
    }
}).change();
于 2011-01-31T09:53:32.283 回答
1

当您查询时,$.data( object, 'events' )您会得到一个带有附加到它的事件属性的对象。所以在你的情况下,你可以添加这个条件:

(function( $ ) {
  $.fn.blah = function(){
    var that = this;
    return this.each(function(){
       if ($.data( $(this).get(0), 'events' ) !== void(0) &&
           $.data( $(this).get(0), 'events' ).change === void(0)) {
           $(this).bind('change', function(){
               // do some stuff here
               return true;
           }).change();
       }
   });
 };
})(jQuery);

...为了仅绑定尚未绑定的函数。

于 2011-01-31T10:03:26.527 回答