views:

81

answers:

4

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 is appreciated.

A: 

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...

jmar777
Well, it'd also be possible to explicitly set the "onclick" attribute from Javascript.
Pointy
A: 
Pointy
+2  A: 

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:

Daniel Vassallo
A: 

Hi

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

kadalamittai