我正在建立一個簡單的腳本,用戶點擊一個藍色按鈕或一個紅色按鈕。當點擊藍色按鈕時,用戶點擊的按鈕應該淡出,這很好。但是,如果用戶點擊紅色按鈕,則淡出的藍色將停止。就像我說的那樣,藍色按鈕可以工作,但紅色按鈕不能。爲什麼我的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);}
}
}
的可能的複製[是匿名函數能夠處理removeEventListener?](http://stackoverflow.com/questions/36637197/are-anonymous-functions-able-to-handle-removeeventlistener) – yezzz