1.事件委托.html 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. <style>
  8. #box1 {
  9. width: 400px;
  10. height: 400px;
  11. background: #00f;
  12. }
  13. #box2 {
  14. width: 200px;
  15. height: 200px;
  16. background: #ff0;
  17. }
  18. </style>
  19. </head>
  20. <body>
  21. <ul>
  22. <li>1</li>
  23. <li>2</li>
  24. <li>3</li>
  25. <li>4</li>
  26. </ul>
  27. <button>添加</button>
  28. <div id="box1">
  29. <div id="box2"></div>
  30. </div>
  31. <script>
  32. // 五种
  33. // document.getElementById id名称的元素 <li>1<li>
  34. // document.querySelector("li") <li>1<li>
  35. // document.getElementsByClassName()[0] []
  36. // document.querySelectorAll() []
  37. // document.getElementsByTagName() []
  38. let btn = document.querySelector("button");
  39. let uls = document.querySelector("ul");
  40. let lis = document.querySelectorAll("li");
  41. console.log(lis,'lis')
  42. uls.onclick = function (event) {
  43. // console.log("111",event)
  44. // 减少内存消耗 避免多次循环
  45. if(event.target.nodeName == "LI") {
  46. console.log(event.target.innerText)
  47. }
  48. }
  49. // lis.forEach((item) => {
  50. // item.onclick = function() {
  51. // console.log(item.innerText)
  52. // }
  53. // })
  54. // btn.onclick = function () { }
  55. btn.addEventListener('click', function () {
  56. // 创建标签
  57. var li1 = document.createElement("li");
  58. // 设置标签内容
  59. // Math.random() 生成随机数
  60. // 固定数值随机生成
  61. // Math.random()*(y-x)+x
  62. li1.innerText = Math.round(Math.random() * 9 + 1)
  63. uls.appendChild(li1);
  64. })
  65. var box1 = document.getElementById("box1");
  66. var box2 = document.getElementById("box2");
  67. // 默认事件冒泡阶段 false
  68. box1.addEventListener("click", function () {
  69. console.log("box111")
  70. }, false)
  71. // removeEventListener 移除事件
  72. // 事件捕获阶段 true
  73. box2.addEventListener("click", function () {
  74. console.log("box222")
  75. }, false)
  76. // 事件:事件捕获 目标阶段 事件冒泡
  77. </script>
  78. </body>
  79. </html>