当前位置:K88软件开发文章中心编程语言JavaScriptJS01 → 文章内容

addEventListener和onclick的区别

减小字体 增大字体 作者:佚名  来源:网上搜集  发布时间:2019-1-4 8:51:35

-->

addEventListeneronclick有什么不一样?于是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.
    下面是中文版的

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<ul id="color-list">
    <li id="addEvent">red</li>
    <li id="on_click">yellow</li>
</ul>
    <script type="text/javascript">
 
            var addEvent = document.getElementById("addEvent");
                    addEvent.addEventListener("click",function(){
                       this.innerHTML = "xxxxx";
                    },false);
                    addEvent.addEventListener("click",function(){
                        this.innerHTML = "xx1111";
                    },false);

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

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

addEventListener和onclick的区别