var element = document.getElementById('testing');element.onclick = function () { alert('did stuff #1'); };element.onclick = function () { alert('did stuff #2'); };
/*Testing that the function returned from bind is rereferenceable,such that it can be added and removed as an event listener.*/function MyImportantCalloutToYou(message, otherMessage) {// the following is necessary as calling bind again does// not return the same function, so instead we replace the// original function with the one bound to this instancethis.swap = this.swap.bind(this);this.element = document.createElement('div');this.element.addEventListener('click', this.swap, false);document.body.appendChild(this.element);}MyImportantCalloutToYou.prototype = {element: null,swap: function() {// now this function can be properly removedthis.element.removeEventListener('click', this.swap, false);}}
Cares about semantics. Basically, it makes registering event handlers more explicit. For a beginner, a function call makes it obvious that something happens, whereas assigning event to some property of DOM element is at least not intuitive.
Allows you to separate document structure (HTML) and logic (JavaScript). In tiny web applications it may not seem to matter, but it does matter with any bigger project. It's way much easier to maintain a project which separates structure and logic than a project which doesn't.
Eliminates confusion with correct event names. Due to using inline event listeners or assigning event listeners to .onevent properties of DOM elements, lots of inexperienced JavaScript programmers thinks that the event name is for example onclick or onload. on is not a part of event name. Correct event names are click and load, and that's how event names are passed to .addEventListener().
const element = document.querySelector('a');element.onclick = event => event.preventDefault();
<a href="//google.com">Try clicking this link.</a>
This was a way to register event handlers in DOM 0. It's now discouraged, because it:
Allows you to register only one event handler. Also removing the assigned handler is not intuitive, because to remove event handler assigned using this method, you have to revert onevent property back to its initial state (i.e. null).
Doesn't respond to errors appropriately. For example, if you by mistake assign a string to window.onload, for example: window.onload = "test";, it won't throw any errors. Your code wouldn't work and it would be really hard to find out why. .addEventListener() however, would throw error (at least in Firefox): TypeError: Argument 2 of EventTarget.addEventListener is not an object.
Doesn't provide a way to choose if you want to handle event in its capturing or bubbling phase.
Inline event handlers (onevent HTML attribute)
Code example:
<a href="//google.com" onclick="event.preventDefault();">Try clicking this link.</a>
// Function to change the content of t2function modifyText() {var t2 = document.getElementById("t2");if (t2.firstChild.nodeValue == "three") {t2.firstChild.nodeValue = "two";} else {t2.firstChild.nodeValue = "three";}}
// add event listener to tablevar el = document.getElementById("outside");el.addEventListener("click", modifyText, false);
onClick:
function initElement() {var p = document.getElementById("foo");// NOTE: showAlert(); or showAlert(param); will NOT work here.// Must be a reference to a function name, not a function call.p.onclick = showAlert;};
function showAlert(event) {alert("onclick Event detected!");}
var clickEvent = document.getElementByID("onclick-eg");var EventListener = document.getElementByID("addEventListener-eg");
clickEvent.onclick = function(){window.alert("1 is not called")}clickEvent.onclick = function(){window.alert("1 is not called, 2 is called")}
EventListener.addEventListener("click",function(){window.alert("1 is called")})EventListener.addEventListener("click",function(){window.alert("2 is also called")})
关于事件委派,实际上可以归结为这个。如果一些其他JavaScript代码需要响应单击事件,使用addEventListener确保你们都可以响应它。如果你们都尝试使用onClick,然后一个踩另一个。如果你想在同一个元素上点击。Furthermore, you want to keep your behavior as separate as you can from the HTML in case you need to change it later. It would suck to have 50 HTML files to update instead of one JavaScript file.(归功于Greg Burghardt,addEventListener vs onClick关于事件委托)