How addEventListener influences the onclick property of DOM element?
element.onclick = function() { alert(1); }
alert(element.onclick);
The above code will output function () { alert(1); }
Then I continue to execute the following code:
element.addEventListener('click', function() { alert(2); }, false);
alert(element.onclick);
The output is still function () { alert(1); }
In fact when clicking on the element now, the code addEventListener('click', function() { alert(2); }, false);
works, it means the new function alert(2)
has written into the onclick
property of this element. But why is the output still unchanged?
So, what I want to know is when executing addEventListener
, how th开发者_运维问答e onclick
property changed?
Looking forward to your reply.
OnClick is a DOM Level 0 property. AddEventListener is part of the DOM Level 2 definition. Adding an event handler via the AddEventListener method does not change the OnClick property on the element, rather it adds the listener to a collection of event listeners on the element. You can find out more about DOM Level 2 events at http://www.w3.org/TR/DOM-Level-2-Events/events.html. There's also a nice article at http://en.wikipedia.org/wiki/DOM_events.
The "onfoo" attributes are independent of the event handler management system accessed via "addEventListener()". It's best to use one or the other, not both, and the right choice is the more flexible and unintrusive "addEventListener()" (where available).
精彩评论