批改状态:合格
老师批语:事件添加方式有多种方式, 只要掌握一到二个就可以 了
<div class="container"><button>按钮1</button><button>按钮2</button><button>按钮3</button></div>
1.通过添加元素属性实现点击事件的添加
const btn1 = document.querySelector(".container>button:nth-of-type(1)");btn1.onclick = () => console.log(123);
2.通过事件监听方法实现事件添加
const btn2 = document.querySelector(".container>button:nth-of-type(2)");btn2.addEventListener("click", () => console.log(456), false);
事件代理的原理是 DOM 的事件冒泡,通过事件委托可以节省大量不必要的代码
<div class="container"><button class="btn1">按钮1</button><button class="btn2">按钮2</button><button class="btn3">按钮3</button></div>
const btn1 = document.querySelector(".container>button:nth-of-type(1)");btn1.onclick = () => console.log("我是按钮1");const btn2 = document.querySelector(".container>button:nth-of-type(2)");btn2.addEventListener("click", () => console.log("我是按钮2"), false);const btn3 = document.querySelector(".container>button:nth-of-type(3)");btn2.addEventListener("click", () => console.log("我是按钮3"), false);
const btn = document.querySelector(".container");btn.addEventListener("click",(e) => {// console.log(typeof e.target.className); //触发的元素 (还有一个相对的绑定 的元素)// console.log(e.currentTarget); //绑定的元素switch (e.target.className) {case "btn1":console.log("我是按钮1");break;case "btn2":console.log("我是按钮2");break;case "btn3":console.log("我是按钮3");break;}},false);
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号