onclick VS addEventListener

[原文]https://stackoverflow.com/questions/6348494/addeventlistener-vs-onclick

一、Inline events(HTML onclick="")

<a id="1" href="#" onclick="javascript:func(this)" >here</a>

<a href="#" onclick="alert('do stuff here');">here<a>
  1. onclick 使用 this,it will returns only the element clicked, even if it is similar to other elements in the DOM.
  2. 一般都会避开直接在 html element 上添加 event,它最明显的不足是:You may not use closures(闭包) or anonymous(匿名) functions here(Though the handler itself is an anonymous function of sorts), and your control of scope is limited.

二、js events(js element.onclick)

element.onclick = function() { /* do stuff here */ };
  1. more control of scope
  2. can use anonymous functions
  3. can use closures
  4. can use function references

注意,onclick最大的缺陷就是:you may only have one inline event assigned. Inline events are stored as an attribute/property of the element, meaning that it can be overwritten.

三、addEventListener / IE's attachEvent(不讨论)

element.addEventListener('click', function() { /* do stuff here */ }, false);

var myFunctionReference = function() { /* do stuff here */ }
element.addEventListener('click', myFunctionReference , false);

注意其第三个参数的作用:选择监听的方式(bubbling or capturing),默认为false,95% 的使用场景都是 false.

addEventListener 相比于 onclick 的优势便是支持注册多个事件绑定到同一个 element,即 you can attach a theoretically unlimited number of events to any single element

四、结语

一般来说,不推荐使用 inline event。不过也有特定的场景更好的选择就是内联事件。但大部分情况你是不知道具体使用场景是否是比较特殊的时候,请避免使用 inline event。

addEventListener 需要考虑的仅仅是浏览器方面的问题,比如兼容,但这并不是问题。

猜你喜欢

转载自blog.csdn.net/hoanFir/article/details/88787157