美文网首页我爱编程
为什么使用addEventListener

为什么使用addEventListener

作者: 青山白衣 | 来源:发表于2018-05-25 23:34 被阅读0次

addEventListener允许给一个事件注册多个监听器,具体解释MDN

click事件调用:html调用与js调用的写法区别
<button id='b1' onclick='print()'>button1</button>
<button id='b2' onclick=''>button2</button>
<button id="b3">button3</button>


function print() {
  console.log(123)
}
b2.onclick = print
事件监听:b3的最后一个onclick会覆盖掉之前所有的onclick,想得到所有的值,使用addEventListener
 b3.onclick = function(){
   console.log('我是button3')
 }
 b3.onclick = function(){
   console.log('我是button3.3')
 }
 b3.onclick = function(){
   console.log('我是button3-3-3')
 }
事件监听(队列:先进先出)addEventListener、removeEventListener
// 写法1 
 b3.addEventListener('click',function(){
   console.log('我是button3')  
 })
 b3.addEventListener('click',function(){
   console.log('我是button3.3')
 })
 b3.addEventListener('click',function(){
   console.log('我是button3-3-3')
 })

// 写法2
f1=function(){
  console.log('我是button3')
}
f2=function(){
  console.log('我是button3.3')
}
f3=function(){
  console.log('我是button3-3-3')
}
b3.addEventListener('click',f1)
b3.addEventListener('click',f2)
b3.addEventListener('click',f3)
b3.removeEventListener('click',f2)
b3.removeEventListener('click',f3)
//写法2 打印结果为 '我是button3',因为队列是预先排完的,所以还没点击时,b3就removeEventListener两个函数f2和f3,所以当点击button3时只剩下了f1
button3只能点击一次,相当于jQuery中的one()
f1=function(){
  console.log('我是button3')
  b3.removeEventListener('click',f1)
}
b3.addEventListener('click',f1)

相关文章

网友评论

    本文标题:为什么使用addEventListener

    本文链接:https://www.haomeiwen.com/subject/rkxadftx.html