在下面的屏幕截图中,有人可以解释为什么你必须将函数“once”传递给button.removeEventListener(“click”,once)吗?我们是否仅仅因为removeEventListener 方法需要两个参数而传递它?此外,考虑到“once”函数也传递到了removeEventListener方法中,“Done”没有被控制台记录多次,这似乎很奇怪。
let button = document.getElementById("button");
function once() {
console.log("Done");
button.removeEventListener("click", once);
}
button.addEventListener("click", once);
<button id="button">once</button>
最佳答案
当你只想解绑特定的处理程序时(比如这里你解绑once
处理程序),你需要将其作为第二个参数传递,否则JS将不知道要删除哪个处理程序。
每个事件可以绑定(bind)多个处理程序。
Additionally, it seems strange that "Done" is not console logged more than once given the "once" function is also passed into the removeEventListener method.
这就是它只被调用一次的原因。您在那里传递函数的引用一次,因此 JS 知道要取消绑定(bind)哪个处理程序。当您调用 removeEventListener
时,它不会调用它。
一旦用户单击按钮,该函数就会被调用,在处理程序中会有这个 console.log
,并且在它之后会立即取消注册,因此后面的单击将不再触发该函数。
关于javascript - Eloquent JavaScript 中的removeEventListener 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46988326/