为什么我的removeEventListener不起作用?
问题描述:
我正在建立一个简单的脚本,用户点击一个蓝色按钮或一个红色按钮。当点击蓝色按钮时,用户点击的按钮应该淡出,这很好。但是,如果用户点击红色按钮,则淡出的蓝色将停止。就像我说的那样,蓝色按钮可以工作,但红色按钮不能。为什么我的removeEventListener不起作用?
看看这里和其他网站的各种问题和答案我相信我的代码是正确的,似乎它不会工作的原因是因为它们不匹配,即我实际上并没有删除添加事件。
我的代码如下任何帮助将不胜感激,我使用Adobe动画到代码:
instance = this;
instance.stop();
//Buttons array
var lowerQuestions = [instance.BTN1, instance.BTN2, instance.BTN4];
//Add an event listener to each button in the array
addEventListeners();
function addEventListeners(){
lowerQuestions.forEach(function(element) {
element.addEventListener("click", function(){
console.log('add listener');
addButtonValue(element);
},false);
});
}
//Remove event listeners when BTN3 is clicked
instance.BTN3.addEventListener("click", removeEventListeners)
function removeEventListeners(){
console.log('prevent');
lowerQuestions.forEach(function(element) {
element.removeEventListener("click", function(){
console.log('remove listener');
addButtonValue(element);
//console.log('hit me here');
},false);
});
}
//Event listener function
function addButtonValue(element){
instance.addEventListener("tick", fadeOut);
element.alpha = 1;
function fadeOut(){
element.alpha -= 0.15;
if(element.alpha <= 0){
instance.removeEventListener("tick", fadeOut);}
}
}
答
对于元素的删除事件监听器,你有两个选择。 1-制作元素的副本,并用这个替换。 2-为侦听器函数放置名称,并将其传递给删除事件侦听器。 在你的代码中,我建议第一个解决方案。此代码可以帮助您,为您要删除侦听器应该运行这段代码的每一个元素:
function removeEventListeners(){
console.log('prevent');
lowerQuestions.forEach(function(element) {
var cln = element.cloneNode(true);
element.parentNode.appendChild(cln);
element.parentNode.removeChild(element);
});
}
答
Are anonymous functions able to handle removeEventListener?讨论了为什么匿名函数表达式是需要被移除事件监听器不是很大 - 函数表达式产生不同函数对象每次执行时,所以remove函数永远不会匹配添加的函数。
在这种情况下,一个简单的解决方案是使用标准命名函数声明创建监听器:
function buttonClicked(){
addButtonValue(this);
}
addEventListeners();
function addEventListeners(){
lowerQuestions.forEach(function(element) {
element.addEventListener("click", buttonClicked, false);
});
}
这名字让听众可拆卸:
//...
lowerQuestions.forEach(function(element) {
element.removeEventListener("click", buttonClicked, false);
});
//...
的可能的复制[是匿名函数能够处理removeEventListener?](http://*.com/questions/36637197/are-anonymous-functions-able-to-handle-removeeventlistener) – yezzz