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

前端之家收集整理的这篇文章主要介绍了列出使用jquery在页面上连接的所有javascript事件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
使用jQuery,是否有可能获得所有事件的列表和事件绑定到哪个元素?

解决方法

jQuery使这相对容易,因为它在元素数据中存储事件处理程序。你应该能够使用这样的东西:
  1. (function($) {
  2. $.eventReport = function(selector,root) {
  3. var s = [];
  4. $(selector || '*',root).andSelf().each(function() {
  5. // the following line is the only change
  6. var e = $.data(this,'events');
  7. if(!e) return;
  8. s.push(this.tagName);
  9. if(this.id) s.push('#',this.id);
  10. if(this.className) s.push('.',this.className.replace(/ +/g,'.'));
  11. for(var p in e) {
  12. var r = e[p],h = r.length - r.delegateCount;
  13. if(h)
  14. s.push('\n',h,' ',p,' handler',h > 1 ? 's' : '');
  15. if(r.delegateCount) {
  16. for(var q = 0; q < r.length; q++)
  17. if(r[q].selector) s.push('\n',' for ',r[q].selector);
  18. }
  19. }
  20. s.push('\n\n');
  21. });
  22. return s.join('');
  23. }
  24. $.fn.eventReport = function(selector) {
  25. return $.eventReport(selector,this);
  26. }
  27. })(jQuery);

你可以调用它:

  1. // all events
  2. alert($.eventReport());
  3.  
  4. // just events on inputs
  5. alert($.eventReport('input'));
  6.  
  7. // just events assigned to this element
  8. alert($.eventReport('#myelement'));
  9.  
  10. // events assigned to inputs in this element
  11. alert($.eventReport('input','#myelement'));
  12. alert($('#myelement').eventReport('input')); // same result
  13.  
  14. // just events assigned to this element's children
  15. alert($('#myelement').eventReport());
  16. 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’)。对上面的函数的更新将如下所示:

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

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

猜你在找的jQuery相关文章