移除JavaScript事件监听器

4

我有以下javascript代码需要激活

document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

但是我在尝试移除事件监听器时遇到了问题。
document.removeEventListener('touchmove', function (e) { e.preventDefault(); }, false);

函数removeEventListener似乎无法正常工作。我在类似情况下做了一些搜索,但不幸的是找不到解决方案。感谢任何帮助。

2个回答

13

你正在向addEventListener调用发送一个匿名函数。改为使用命名函数,并将其发送到removeEventListener中,就像这样:

function handleTouchMove(e) {
  e.preventDefault();
}
document.addEventListener('touchmove', handleTouchMove, false);

document.removeEventListener('touchmove', handleTouchMove);
否则,如果您按照之前的方式操作,将函数发送到removeEventListener中,即使它具有相同的内容,它仍然是一个完全不同的函数。

1
更多有关正确使用的阅读资料: https://developer.mozilla.org/zh-CN/docs/Web/API/EventTarget/removeEventListener - Andreas Eriksson
哇,感谢霍华德提供这个并解释。我现在明白了。也感谢安德烈亚斯提供的文章链接。 - Chinchan Zu

2
您需要像这样传递完全相同的函数引用:

您必须传递完全相同的函数引用,如下所示:

function handleTouch(e) {
    e.preventDefault();
}

document.addEventListener('touchmove', handleTouch, false);

document.removeEventListener('touchmove', handleTouch, false);

即使两个匿名函数的代码相同,也不能使用第二个副本。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接