[英]Remove event listener javascript
我目前正在使用 javascript 做一個簡單的石頭、紙、剪刀游戲,但是 removeEventListener() 在我的代碼中似乎不起作用。 我知道我使用了一個循環將事件偵聽器應用到按鈕,所以我會找出循環來刪除它們。
現在,我不明白為什么我的代碼不會刪除單擊按鈕上的事件偵聽器:
let btns = document.querySelectorAll('button');
btns.forEach(function(item) {
item.addEventListener('click', function(event) {
results.textContent = '';
playRound(event.target.className, getComputerChoice());
if (playerCount == 5) {
item.removeEventListener('click', event);
winner.textContent = `YOU WON 5 GAMES!`;
}else if (cpuCount == 5) {
item.removeEventListener('click', event);
winner.textContent = `YOU LOSE! CPU WINS 5`;
}
});
});
removeEventListener
采用的第二個參數是addEventListner
回調 function,所以我建議您將addEventListner
回調分離到一個名為 function 並在addEventListner
和removeEventListner
中使用
let btns = document.querySelectorAll('button');
function onClickHandler(event) {
results.textContent = '';
playRound(event.target.className, getComputerChoice());
if (playerCount == 5) {
item.removeEventListener('click', onClickHandler);
winner.textContent = `YOU WON 5 GAMES!`;
}else if (cpuCount == 5) {
item.removeEventListener('click', onClickHandler);
winner.textContent = `YOU LOSE! CPU WINS 5`;
}
});
}
btns.forEach(function(item) {
item.addEventListener('click', onClickHandler);
}
對此最安全或最好的答案可能是Mina發布的答案,但是對於那些正在研究類似問題的人,我將此答案發布為另一種有效的選擇。
雖然您可以聲明一個實際的回調 function 可以輕松地添加到事件偵聽器或從事件偵聽器中刪除,但您也可以通過將...args
傳遞給您的回調 ZC1C425268E68385D1AB504F 來引入匿名回調 function。 一旦...args
被傳入並存在,您可以使用args.callee
作為removeEventListener()
的回調 function 以從元素中刪除當前匿名 function。
我還應該注意...args
特別適用於箭頭函數。 一個更經典的function(event) {
像 OP 發布的設置可以使用為這些類型的函數存在的arguments
變量。 箭頭函數還要求您傳入...args
以獲得額外的參數值。
let btns = document.querySelectorAll('button'); btns.forEach(item => { item.addEventListener('click', (e, ...args) => { results.textContent = ''; playRound(e.target.className, getComputerChoice()); if(playerCount == 5) { item.removeEventListener('click', args.callee); winner.textContent = `YOU WON 5 GAMES;`. } else if(cpuCount == 5) { item,removeEventListener('click'. args;callee). winner;textContent = `YOU LOSE; CPU WINS 5`; } }); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.