addEventListener STILL多次触发(即使具有相同名称的回调)

问题描述 投票:0回答:1

下面的代码仅将一个事件应用于多个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);
    }
}
javascript javascript-events addeventlistener
1个回答
0
投票

这是因为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");
}
© www.soinside.com 2019 - 2024. All rights reserved.