addEventListener和onclick的区别

来源:互联网 发布:数据库在企业中的应用 编辑:程序博客网 时间:2024/06/05 20:07

今天在温习犀牛书的时候,正好看到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.
    下面是中文版的
    这里写图片描述
    参考如下:
    这个是英文版本的 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>
1 0
原创粉丝点击