window对象DOMContentLoaded事件removeEventListener失效求助
问题根源与解决方案
你现在的问题根本不是window对象的问题,而是**DOMContentLoaded事件在你点击按钮之前就已经触发执行过了**。这个事件只会在DOM首次加载完成时触发一次,触发后对应的changeColor监听器已经执行完毕,你后续调用removeEventListener移除它,对已经执行过的代码没有任何影响——它既不会撤销changeColor里给颜色选择器添加的input监听器,也不会改变任何已经发生的操作。
你真正需要做的,是移除colorSelector上的input事件监听器,而不是去动DOMContentLoaded的监听器。要实现这个,你需要保存input监听器的引用,不能用匿名函数,因为匿名函数无法被removeEventListener识别。
修改后的代码示例:
// 保存input监听器的引用 function handleColorChange(event) { const sectionToChange = document.querySelector("section:has(#color-select)"); const colorSelector = event.target; sectionToChange.style.cssText += `background-color: ${colorSelector.value}`; } window.addEventListener("DOMContentLoaded", changeColor, true); function changeColor() { const colorSelector = document.querySelector("#color-select"); // 使用命名函数作为监听器 colorSelector.addEventListener("input", handleColorChange); } window.addEventListener("DOMContentLoaded", removeEvents); function removeEvents() { const removeListenersButton = document.querySelector("#remove-listeners"); removeListenersButton.addEventListener("click", () => { console.log("clicked"); const colorSelector = document.querySelector("#color-select"); // 移除input监听器 colorSelector.removeEventListener("input", handleColorChange); }); };
关键要点:
removeEventListener必须传入与添加时完全相同的函数引用,匿名函数无法满足这一点,因为每次创建的匿名函数都是不同的引用。DOMContentLoaded事件是一次性的,触发后再移除它的监听器没有实际意义,它不会影响监听器内部已经完成的操作。
内容的提问来源于stack exchange,提问作者newbdev2022
相关产品推荐
相关产品推荐

