首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何删除EventListener?

问如何删除EventListener?
EN

Stack Overflow用户
提问于 2022-08-24 10:00:05
回答 1查看 60关注 0票数 2

如何删除EventListener?附件是它不起作用的一个快速例子。怎么才是正确的呢?

代码语言:javascript
复制
function test_function(a='', b='') {    
    console.log('test_function started. a='+a+', b='+b);    
}

document.body.addEventListener('mousemove', ()=>{   test_function('testa', 'testb');    });
document.body.removeEventListener("mousemove", test_function );
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-08-24 10:07:53

test_function不是事件处理程序的事件侦听器函数。它是

()=>{ test_function('testa', 'testb')这个匿名函数。

在这个document.body.removeEventListener("mousemove", test_function );中,您将test_function的引用传递给removeEventListener。但实际的功能是()=>{ test_function('testa', 'testb')

为了使用removeEventListener,您可以以这种方式重构代码。

代码语言:javascript
复制
function test_function(a='', b='') {    
    console.log('test_function started. a='+a+', b='+b);    
}

const handleMouseMove = () => test_function('testa', 'testb');

document.body.addEventListener('mousemove', handleMouseMove);
document.body.removeEventListener("mousemove", handleMouseMove);

查看mdn文档,

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73471141

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档