用on的代码:

window.onload = function(){
  var box = document.getElementById("box");
  box.onclick = function(){
  console.log("我是box1");
}
box.onclick = function(){
  box.style.fontSize = "18px";
  console.log("我是box2");
  }
}
     运行结果:“我是box2”

第二个onclick把第一个onclick给覆盖了,虽然大部分情况我们用on就可以完成我们想要的结果,但是有时我们又需要执行多个相同的事件,很明显如果用on完成不了我们想要的,addEventListener可以多次绑定同一个事件并且不会覆盖上一个事件。

用addEventListener的代码:

window.onload = function(){
  var box = document.getElementById("box");
  box.addEventListener("click",function(){
  console.log("我是box1");
})
box.addEventListener("click",function(){
    console.log("我是box2");
  })
}
    运行结果:我是box1
         我是box2

相关文章:

  • 2022-02-07
  • 2022-02-01
  • 2022-01-18
  • 2022-12-23
  • 2022-01-06
  • 2021-08-08
  • 2022-12-23
猜你喜欢
  • 2021-05-29
  • 2022-03-11
  • 2022-12-23
  • 2021-10-05
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案