使用 jQuery,是否可以获取所有事件的列表以及事件绑定(bind)到哪个元素?
最佳答案
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', p, ' 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
更新: 我在上述函数的输出中添加了一些处理程序和一些有关委托(delegate)事件的信息。
更新(2012 年 8 月 24 日):
虽然上述函数在 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) {
var s = [];
$(selector || '*', root).addBack().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', p, ' for ', r[q].selector);
}
}
s.push('\n\n');
});
return s.join('');
}
$.fn.eventReport = function(selector) {
return $.eventReport(selector, this);
}
})(jQuery);
更新(2013 年 4 月 25 日):
andSelf()
从 1.8.x 开始被弃用 http://bugs.jquery.com/ticket/9800 ,我用 addBack()
代替。
关于javascript - 使用 jquery 列出页面上连接的所有 javascript 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/743876/