【发布时间】:2021-05-17 17:43:14
【问题描述】:
我在按钮上创建了一个带有事件侦听器的函数搜索。问题是 removeEventListener 不起作用,因为 init() 在其中执行。因此,每次单击按钮时都会复制 EventListener。如果我删除 init() 一切都很好。也许我误解了它?
另外,如果我删除函数搜索并且只使用 const 我知道它会触发。但重点是我需要使用搜索。
function search(data) {
const clickHandler = () => {
console.log('search');
init();
};
document.getElementById('search').removeEventListener('click', clickHandler);
document.getElementById('search').addEventListener('click', clickHandler);
}
search(data);
function init() {
console.log('hello');
}
console results:
first time; hello
second time; hello hello
third time; hello hello hello hello
【问题讨论】:
-
问题是您试图删除与添加的功能不同的功能。与init无关。当您调用搜索时,它会产生一个新功能。它与您上次调用它时创建的函数不同。
-
我非常怀疑这是真的,因为我在下面的答案中的代码没有使用 init 并且有同样的问题。
标签: javascript event-handling dom-events