addEventListener和onclick的区别

付费节点推荐

免费节点

节点使用教程

Clash 小火箭 v2ray节点购买

好用的梯子,海外网络,快速稳定

Google

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

#addEventListener #javascript #onclick
评论(0)
游客的头像
表情
全部评论
最新