addEventListener和onclick的区别

时间:2021-12-10 19:36:34

今天在温习犀牛书的时候,正好看到17章,突然有个疑问,addEventListener和onclick有什么不一样?于是Google查了下,然后用写了个小demo去比较它们,

addEventListener is the way to register an event listener as specified in W3C DOM. Its benefits are as follows:

  1. It allows adding more than a single handler for an event. This is particularly useful for DHTML libraries or Mozilla extensions that need to work well even if other libraries/extensions are used.
  2. It gives you finer-grained control of the phase when the listener gets activated (capturing vs. bubbling)
  3. It works on any DOM element, not just HTML elements.
    下面是中文版的
    addEventListener和onclick的区别
    参考如下:
    这个是英文版本的 https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
    这个是中文版本的https://developer.mozilla.org/zh-CN/docs/Web/API/EventTarget/addEventListener

demo如下,得出结果onclick只出现一次alert:我是click2【很正常第一次click事件会被第二次所覆盖】,但是addEventListener却可以先后运行,不会被覆盖【正如:它允许给一个事件注册多个监听器。在使用DHTML库或者 Mozilla extensions 这样需要保证能够和其他的库或者差距并存的时候非常有用。】

<ul id="color-list">
<li id="addEvent">red</li>
<li id="on_click">yellow</li>
</ul>
<script type="text/javascript">
(function(){
var addEvent = document.getElementById("addEvent");
addEvent.addEventListener("click",function(){
alert("我是addEvent1");
},false);
addEvent.addEventListener("click",function(){
alert("我是addEvent2");
},false);

var addEvent = document.getElementById("on_click");

on_click.onclick = function() {
alert("我是click1");
}
on_click.onclick = function() {
alert("我是click2");
}
})();
</script>