Blogger Information
Blog 21
fans 0
comment 0
visits 14739
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
(1104)事件添加方式和事件代理
Yuming
Original
750 people have browsed it

(1104)事件添加方式和事件代理

事件添加方式,重点是监听器,实例演示

  1. <div class="container">
  2. <button>按钮1</button>
  3. <button>按钮2</button>
  4. <button>按钮3</button>
  5. </div>
  • 事件添加方式

1.通过添加元素属性实现点击事件的添加

  1. const btn1 = document.querySelector(".container>button:nth-of-type(1)");
  2. btn1.onclick = () => console.log(123);

2.通过事件监听方法实现事件添加

  1. const btn2 = document.querySelector(".container>button:nth-of-type(2)");
  2. btn2.addEventListener("click", () => console.log(456), false);

事件代理的实现原理,实例演示

事件代理的原理是 DOM 的事件冒泡,通过事件委托可以节省大量不必要的代码

  1. <div class="container">
  2. <button class="btn1">按钮1</button>
  3. <button class="btn2">按钮2</button>
  4. <button class="btn3">按钮3</button>
  5. </div>
  • 普通方式添加事件监听
  1. const btn1 = document.querySelector(".container>button:nth-of-type(1)");
  2. btn1.onclick = () => console.log("我是按钮1");
  3. const btn2 = document.querySelector(".container>button:nth-of-type(2)");
  4. btn2.addEventListener("click", () => console.log("我是按钮2"), false);
  5. const btn3 = document.querySelector(".container>button:nth-of-type(3)");
  6. btn2.addEventListener("click", () => console.log("我是按钮3"), false);
  • 以下是事件代理添加事件监听
  1. const btn = document.querySelector(".container");
  2. btn.addEventListener(
  3. "click",
  4. (e) => {
  5. // console.log(typeof e.target.className); //触发的元素 (还有一个相对的绑定 的元素)
  6. // console.log(e.currentTarget); //绑定的元素
  7. switch (e.target.className) {
  8. case "btn1":
  9. console.log("我是按钮1");
  10. break;
  11. case "btn2":
  12. console.log("我是按钮2");
  13. break;
  14. case "btn3":
  15. console.log("我是按钮3");
  16. break;
  17. }
  18. },
  19. false
  20. );
Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:事件添加方式有多种方式, 只要掌握一到二个就可以 了
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post