javascript - Eloquent JavaScript 中的removeEventListener 示例

标签 javascript function methods callback addeventlistener

在下面的屏幕截图中,有人可以解释为什么你必须将函数“once”传递给button.removeEventListener(“click”,once)吗?我们是否仅仅因为removeEventListener 方法需要两个参数而传递它?此外,考虑到“once”函数也传递到了removeEventListener方法中,“Done”没有被控制台记录多次,这似乎很奇怪。

enter image description here

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/

相关文章:

javascript - 使用 Knockout.js 中的新项目更新可观察数组的位置

javascript - jquery 关闭不工作

python - 列表中 10 的倍数

python - 将参数传递给 Python 的函数

c - 编译两个C文件时不需要函数声明

ruby - 非阻塞ruby数据处理或方法调用

java - 为什么java方法不支持多个返回值?

javascript - 在 Scala Play Framework View 中使用键检索映射值

使用参数调用 obj-c 方法

javascript - 使用socket.io与其他javascript文件nodejs和express发送和获取数据