【问题标题】:jQuery & livequery - check if a function has been attached to a elementjQuery & livequery - 检查函数是否已附加到元素
【发布时间】:2011-06-18 11:26:24
【问题描述】:

我正在运行这个:

$("*: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() 是否已经应用于输入元素并停在那里?

【问题讨论】:

    标签: jquery livequery


    【解决方案1】:

    老实说,我不会那样做。您的第一条语句是一个很大的 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();
    

    【讨论】:

    • 既然她只想要那些不在#boo 中的人,我认为您的过滤功能中应该只有一个!...无论如何,+1
    【解决方案2】:

    当您查询$.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);
    

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

    【讨论】:

      猜你喜欢
      • 2010-12-13
      • 2017-12-30
      • 2015-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多