下面的代码仅将一个事件应用于多个DOM元素。由于将多次调用此代码集,因此事件将多次应用于同一元素。
我避免再次分配它们(通过使用相同的回调函数而不是匿名函数),但是它们仍然被应用并触发多次。我在这里没看到什么?
//apply delete event listener to all list items
function applyListener(){
let delBtnS = document.querySelectorAll(".toDoList li span")
let checkOff = document.querySelectorAll(".toDoList li");
//separate function won't have event applied multiple times
let applyCompleted = function(){
console.log("Apply has been pressed");
}
let applyDelete = function(event){
console.log("Delete has been pressed");
}
//checkOff
for (let item of Array.from(checkOff)){
item.addEventListener("click", applyCompleted);
}
//delete button
for (let btn of Array.from(delBtnS)){
btn.addEventListener("click", applyDelete);
}
}
这是因为DOM树上的事件propagates,这意味着即使事件发生在子代事件上,它的父代也会做出反应。您需要使用stopPropagation
let applyDelete = function(event){
event.stopPropagation(); // click on <span> won't travel to it's parent <li>
console.log("Delete has been pressed");
}