开发者

Getting back the event handler returns undefined

开发者 https://www.devze.com 2023-01-10 15:43 出处:网络
The following codes don\'t work: function dnd(){ } var ele = document.getElementById(\"relative\"); ele.addEventListener(\"click\",dnd,false);

The following codes don't work:

function dnd(){
}
var ele = document.getElementById("relative");
ele.addEventListener("click",dnd,false);
document.write(ele.onclick);

the output is undefined. I guess the output should be function onclick(event){dnd();}

What should I do to solve this problem?

Any suggestion i开发者_JAVA技巧s appreciated.


There are 3 common ways to attach events to DOM nodes.

The addEventListener() method is the way to register an event listener as specified in W3C DOM. It has many benefits, but doesn't work in Internet Explorer. For Internet Explorer you'd have to use the attachEvent() method, which offers similar functionality.

On the other hand, the onclick property is an older, but more supported way to attach event handlers. However it has certain disadvantages, such as allowing just one event handler for each event.

As for how to get back the event handlers that are attached to a particular node, it depends on the method you use to attach the events. The problem with your example is that you're using the addEventListener() method to attach the event, and then trying to read it using the onclick property.

You may want to check out the following Stack Overflow post for further reading into this topic, especially the post by @Crescent Fresh:

  • How to find event listeners on a DOM node?


The onclick property is only going to show you an event handler if it is registered inline via the markup (e.g, <div id="relative" onclick="alert('foo');"></div>).

Why do you need to read the event handler? This is a relatively strange thing to do...


There are different ways of establishing event handlers, and they use different mechanisms inside the DOM. In particular — and as you've discovered empirically — adding an event listener via "addEventListener" does not affect the "onclick" attribute of the element. The mechanisms are simply separate.


This is one of the current limitation of W3C event registration model. if you register using JS methods then there is no standard way to get the handlers.

Latest DOM LEVEL 3 Events W3C adds eventListenerList spec. i guess we are lacking of some close support for this API across browsers.

Of-course if you add your method using tradition way



      


then your example would work.

Some StackOverFlow Links

link text

0

精彩评论

暂无评论...
验证码 换一张
取 消