2017-05-07 105 views
0

我正在建立一個簡單的腳本,用戶點擊一個藍色按鈕或一個紅色按鈕。當點擊藍色按鈕時,用戶點擊的按鈕應該淡出,這很好。但是,如果用戶點擊紅色按鈕,則淡出的藍色將停止。就像我說的那樣,藍色按鈕可以工作,但紅色按鈕不能。爲什麼我的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

的可能的複製[是匿名函數能夠處理removeEventListener?](http://stackoverflow.com/questions/36637197/are-anonymous-functions-able-to-handle-removeeventlistener) – yezzz

回答

0

對於元素的刪除事件監聽器,你有兩個選擇。 1-製作元素的副本,並用這個替換。 2-爲偵聽器函數放置名稱,並將其傳遞給刪除事件偵聽器。 在你的代碼中,我建議第一個解決方案。此代碼可以幫助您,爲您要刪除偵聽器應該運行這段代碼的每一個元素:

function removeEventListeners(){ 
    console.log('prevent'); 

    lowerQuestions.forEach(function(element) { 
     var cln = element.cloneNode(true); 
     element.parentNode.appendChild(cln); 
     element.parentNode.removeChild(element); 
    }); 
} 
0

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); 
}); 

//...