17_DOM绑定事件.html 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. <button id="btn">按钮</button>
  10. <script>
  11. var oBtn = document.getElementById("btn");
  12. // oBtn.onclick = function(){
  13. // console.log("按钮被点击了")
  14. // }
  15. // oBtn.onclick = function(){
  16. // console.log("hello");
  17. // }
  18. // 移除事件
  19. // oBtn.onclick = null;
  20. // var a = 10;
  21. // var a = 20;
  22. // 通过 addEventListener 绑定事件
  23. // 接收三个参数 第一个事件名称 第二个事件处理函数 第三个布尔值是否冒泡
  24. // oBtn.addEventListener("click",function(){
  25. // console.log("按钮被点击了");
  26. // });
  27. // oBtn.addEventListener("click",function(){
  28. // console.log("hello");
  29. // });
  30. // 两个匿名函数 及时内部方法一摸一样 都不是同一个函数
  31. function foo(){
  32. console.log("按钮被点击了")
  33. }
  34. oBtn.addEventListener("click",foo);
  35. // 移除事件
  36. // removeEventListener 要移除的事件内的参数一定要跟绑定事件时的参数一模一样
  37. oBtn.removeEventListener("click",foo);
  38. </script>
  39. </body>
  40. </html>