Javascript removeEventListener 不起作用 [英] Javascript removeEventListener not working
问题描述
我有以下代码来添加事件监听器
I have the following code to add eventListener
area.addEventListener('click',function(event) {
app.addSpot(event.clientX,event.clientY);
app.addFlag = 1;
},true);
它按预期正常工作..后来在另一个函数中,我尝试使用以下代码删除事件侦听器
It is working correctly as expected..Later in another function i tried to remove the event listener using the following code
area.removeEventListener('click',function(event) {
app.addSpot(event.clientX,event.clientY);
app.addFlag = 1;
},true);
但是偶数监听器没有被移除..为什么会发生?我的removeEventListener()有什么问题吗?注意:这里的区域类似于 document.getElementById('myId')
But the even listener is not removed..Why is it happening?Is there any problem with my removeEventListener()? Note:Here area is something like document.getElementById('myId')
推荐答案
这是因为两个匿名函数是完全不同的函数.您的 removeEventListener
的参数不是对先前附加的函数对象的引用.
This is because that two anonymous functions are completely different functions. Your removeEventListener
's argument is not a reference to the function object that was previously attached.
function foo(event) {
app.addSpot(event.clientX,event.clientY);
app.addFlag = 1;
}
area.addEventListener('click',foo,true);
area.removeEventListener('click',foo,true);
这篇关于Javascript removeEventListener 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!