我目前正在嘗試在單擊按鈕時洗掉事件偵聽器(請參見下面的代碼),但它永遠不會起作用,我知道我應該使用相同的函式來取消事件(此處為keyboardControl)但它似乎沒有要作業。提前致謝
<button class="start">start</button>
<button class="stop">stop</button>
const start = document.querySelector(".start")
const stopbtn = document.querySelector(".stop")
start.addEventListener("click", () => keyboardControl())
stopbtn.addEventListener("click", () => {
document.removeEventListener("keydown", keyboardControl)
})
function keyboardControl() {
document.addEventListener("keydown", (e) => {
switch(e.keyCode) {
case 37: //left arrow key
console.log("left")
break
case 39:
console.log("right")
break
}
})
}
uj5u.com熱心網友回復:
您必須將相同的函式removeEventListener傳遞給傳遞給addEventListener. 您傳遞給的函式addEventListener是
(e) => {
switch(e.keyCode) {
case 37: //left arrow key
console.log("left")
break
case 39:
console.log("right")
break
}
}
由于您沒有在任何無法洗掉它的地方存盤對它的參考。將該函式分配給變數并使用它來添加和洗掉它:
const start = document.querySelector(".start")
const stopbtn = document.querySelector(".stop")
function handleKey(e) {
switch (e.keyCode) {
case 37: //left arrow key
console.log("left")
break
case 39:
console.log("right")
break
}
}
function keyboardControl() {
document.addEventListener("keydown", handleKey);
}
start.addEventListener("click", () => keyboardControl())
stopbtn.addEventListener(
"click",
() => document.removeEventListener("keydown", handleKey)
)
<button class="start">start</button>
<button class="stop">stop</button>
由于多種原因,洗掉keyboardControl不起作用:
- 它實際上不是您要洗掉的處理程式。該函式添加了另一個事件處理程式,但洗掉它不會自動洗掉它添加的處理程式。
keyboardControl永遠不會作為事件處理程式系結到document.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/452215.html
標籤:javascript dom
