微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

列出使用jquery在页面上连接的所有javascript事件

使用jQuery,是否有可能获得所有事件的列表和事件绑定到哪个元素?

解决方法

jQuery使这相对容易,因为它在元素数据中存储事件处理程序。你应该能够使用这样的东西:
(function($) {
    $.eventReport = function(selector,root) {
        var s = [];
        $(selector || '*',root).andSelf().each(function() {
            // the following line is the only change
            var e = $.data(this,'events');
            if(!e) return;
            s.push(this.tagName);
            if(this.id) s.push('#',this.id);
            if(this.className) s.push('.',this.className.replace(/ +/g,'.'));
            for(var p in e) {
                var r = e[p],h = r.length - r.delegateCount;
                if(h)
                    s.push('\n',h,' ',p,' handler',h > 1 ? 's' : '');
                if(r.delegateCount) {
                    for(var q = 0; q < r.length; q++)
                        if(r[q].selector) s.push('\n',' for ',r[q].selector);
                }
            }
            s.push('\n\n');
        });
        return s.join('');
    }
    $.fn.eventReport = function(selector) {
        return $.eventReport(selector,this);
    }
})(jQuery);

你可以调用它:

// all events
alert($.eventReport());

// just events on inputs
alert($.eventReport('input')); 

// just events assigned to this element
alert($.eventReport('#myelement')); 

// events assigned to inputs in this element
alert($.eventReport('input','#myelement')); 
alert($('#myelement').eventReport('input')); // same result

// just events assigned to this element's children
alert($('#myelement').eventReport()); 
alert($.eventReport('*','#myelement'); // same result

更新:
添加了一些处理程序和一些关于委托事件的信息到上述函数输出

UPDATE(8/24/2012):
虽然上面的函数仍然在jQuery 1.7.2和更低版本中工作,jQuery不再存储事件对象在jQuery.data(elem,’events’),如果你使用jQuery 1.8或更高版本,你将不能再使用功能上面!

作为jQuery.data(elem,’events’)的交换,你现在可以使用jQuery._data(elem,’events’)。对上面的函数的更新将如下所示:

(function($) {
    $.eventReport = function(selector,root).addBack().each(function() {
            // the following line is the only change
            var e = $._data(this,this);
    }
})(jQuery);

UPDATE(4/25/2013):
andSelf()已从1.8.x http://bugs.jquery.com/ticket/9800中弃用,我改用addBack()。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐