如何找到任何元素的绑定事件

时间:2011-07-01 07:20:57

标签: javascript jquery html events event-handling

让,

<span onclick="foo()" onfocus="goo()">Have Event</span>

这里我举一个例子。这里有span两个事件都有绑定。

是否有任何 javascript jquery 方式来查找所有与任何html元素绑定的事件?

4 个答案:

答案 0 :(得分:3)

你不能使用DOM2风格的事件处理程序(添加了addEventListener / attachEvent的),这几乎意味着你不想这样做,因为DOM2 +处理程序越来越多的方式它应该完成(tm)

您在示例中显示的是DOM0事件处理程序,但可以检查:您可以遍历元素上的属性,查看已启动的属性用“on”,看看它们是否有值:

var element = document.getElementById("theSpan");
var name;
for (name in element) {
    if (name.substring(0, 2) === "on" && element[name]) {
        // It has a DOM0 handler for the event named by `name`
    }
}

<强>更新

显然,至少在Chrome上,onXyz属性是不可枚举的,因此它们不会显示在for..in循环中。在Firefox上,您只能看到以编程方式分配的内容,而不是通过属性分配。

因此,您可以明确地测试它们:

if (element.onclick) {
    // It has a DOM0-style `click` handler
}

...但你必须有一份你想知道的清单。

以下是一个示例(live copy):

HTML:

<p id="thePara" onclick="foo()">This is the paragraph</p>
<script>
  // Some other bit of code setting a DOM0 handler programmatically
  document.getElementById("thePara").onmousedown = function() {
    display("<code>onmousedown</code> called for thePara");
  };
</script>

JavaScript的:

window.onload = function() {
  // Look up all handlers on thePara
  var element = document.getElementById("thePara");
  var name;
  var names = "onclick onmousedown onchange onmouseup".split(" ");
  var index;

  for (name in element) {
    if (name.substring(0, 2) === "on" && element[name]) {
      display("[loop check] thePara has handler for <code>" + name + "</code>");
    }
  }

  for (index = 0; index < names.length; ++index) {
    name = names[index];
    if (element[name]) {
      display("[explicit check] thePara has handler for <code>" + name + "</code>");
    }
  }
};

function display(msg) {
  var p = document.createElement('p');
  p.innerHTML = msg;
  document.body.appendChild(p);
}

function foo() {
  display("<code>foo</code> called");
}

再次注意,您可能不想这样做,因为您会错过DOM2 +处理程序。

另请注意,单击元素时可能会处理某个事件,即使该元素没有事件的事件处理程序 - 因为事件可以冒泡到父级,查看event.target,查看相关的孩子,并采取适当的行动。这就是事件委托的工作方式,而且它也越来越成功(tm),所以...: - )

答案 1 :(得分:1)

如果我记得很清楚,.data('events')会存储该元素的所有绑定事件。

  

在jQuery 1.4.3中设置元素   带有.data(obj)的数据对象   以前存储的数据   元件。 jQuery本身使用了   .data()方法保存信息   在“事件”和“处理”的名称下,   并保留任何数据名称   以下划线('_')开头   内部使用。

jQuery .data()

此方法仅适用于通过jQuery绑定的事件。

答案 2 :(得分:1)

我不知道如何获得所有活动,但我们可以通过指定它来获得它。 以下是用于跟踪onclick,onfocus和onblur的元素和事件的JQuery代码。

<div id="log"></div>
<script language="javascript">
$('*[onclick],*[onblur],*[onfocus]').each(function () {
    if($(this).attr('onclick'))
    $('#log').html($('#log').html()+'<br>'+this.tagName+' : onclick : '+$(this).attr('onclick'));
    if($(this).attr('onblur'))
    $('#log').html($('#log').html()+'<br>'+this.tagName+' : onblur : '+$(this).attr('onblur'));
    if($(this).attr('onfocus'))
    $('#log').html($('#log').html()+'<br>'+this.tagName+' : onfocus : '+$(this).attr('onfocus'));
});
</script>

答案 3 :(得分:0)

如果仅仅是为了好奇,并且您不需要任何脚本进一步处理此数据,您可以使用visual event bookmarklet