addEventListener和onclick的区别

付费节点推荐


免费节点


节点使用教程


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.
    下面是中文版的
    这里写图片描述

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

  • red
  • yellow

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"); }

未经允许不得转载:Bcoder资源网 » addEventListener和onclick的区别

相关推荐

更多优质资源关注微信公众号: bcoder

bcoder
赞 (0)
分享到:更多 ()

评论 0

评论前必须登录!

登陆 注册