【问题标题】:How do I know whether there is a specific listener on an element in jQuery?我如何知道 jQuery 中的元素上是否有特定的侦听器?
【发布时间】:2010-01-14 15:27:17
【问题描述】:

或者我怎么知道下面这个是否已经运行:

$target.bind('click',function() {
...
});

【问题讨论】:

标签: jquery events


【解决方案1】:

我使用visual event bookmarklet 向我显示哪些项目有事件。

【讨论】:

【解决方案2】:

借用和扩展大卫的例子,使用这个:

if(typeof $('#id').click == 'function') {}

【讨论】:

    【解决方案3】:

    您可以访问jQuery.data 对象来查找:

    $.fn.isBound = function() {
        return this.length && typeof $.data(this[0], 'handle') == 'function' || false;
    }
    
    if ($target.isBound()) {
        // $target has events
    }
    

    更新:如果您想检查特定类型,可以查看 events 对象:

    $.fn.isBound = function(type) {
        return this.length && $.data(this[0], 'events')[type] || false;
    }
    
    if ($target.isBound('click')) {
        // $target has clickevents
    }
    

    【讨论】:

    • 我需要知道click handler 是否被绑定
    【解决方案4】:

    您可以使用 $._data。 例如

    $target.bind('click',function() {
    ...
    });
    
    $._data( $target[0], 'events'); // Object {click: Array[1]}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-20
      • 2015-07-26
      • 1970-01-01
      相关资源
      最近更新 更多