Pre*_*aul 92
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);
Run Code Online (Sandbox Code Playgroud)
你可以称之为:
// 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
Run Code Online (Sandbox Code Playgroud)
更新: 我在上述函数的输出中添加了一些处理程序和一些有关委托事件的信息.
更新(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);
Run Code Online (Sandbox Code Playgroud)
更新(2013年4月25日):
andSelf()从1.8.x http://bugs.jquery.com/ticket/9800弃用,我改为替换addBack().
// List bound events
console.log($('#elem').data('events'));
// Log ALL handlers for ALL events
$.each($('#elem').data('events'), function(i, event) {
$.each(event, function(i, handler){
console.log(handler.toString());
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29734 次 |
| 最近记录: |