What's the difference using addEventListner and simply Onclick/Ondblclick calling a f开发者_开发百科unction(s)?
The onclick etc. are the DOM Level 0 events. They work in every browser but they don't allow you to easily add multiple handlers to the same event in the same element. That means that using something like
window.onload = function () {
// THE CODE TO RUN
};
will remove any function that was already there, so you have to use tricks like:
(function (oldonload) {
window.onload = function () {
// THE CODE TO RUN
oldonload();
};
}(window.onload));
With addEventListener you don't have to do it. You just write:
window.addEventListener("load", function () {
// THE CODE TO RUN
}, false);
and it just works... but not on IE! On IE you have to use attachEvent, which in turn doesn't work anywhere except IE. So you still have to write code like this:
function yourCode () {
// THE CODE TO RUN
}
if (window.addEventListener) {
window.addEventListener('load', yourCode, false);
} else {
window.attachEvent('onload', yourCode);
}
And in all cases you also have to check if the document has already loaded so you just run your code instantly instead of binding it to the event that has already happened and will not happen again - which means even more code:
function yourCode () {
// THE CODE TO RUN
}
if(document.loaded) {
yourCode();
} else {
if (window.addEventListener) {
window.addEventListener('load', yourCode, false);
} else {
window.attachEvent('onload', yourCode);
}
}
The point is that if you want your event handling code to be robust and compatible with all browsers, then it quickly gets very complicated. That's why I always recommend using a library like jQuery to work it out for you so you don't have to worry about those details and just write:
$('some-id').click(function () {
// THE CODE TO RUN
});
and it magically works on every browser.
addEventListner allows you to add more than one listener.
When you're adding an onclick/onmouseover directly on a node you're coupling structure/data with behavior, which isn't good especially if you care about being able to maintain your code.
By decoupling them (using addEventListener) you: (a) gain the ability to make incremental changes to the HTML separately from your JS (and vice-versa), (b) have the ability to reuse the same JS on different HTML (say on another page), (c) gain the ability to cache the JS separately (assuming you have it in an external file), thus improving the over-all performance a bit.
On top of that (as @JohnPick answered) it allows you to add more than one listener to the same node.
精彩评论