這是我正在使用的事件監聽器:
const eventHandler=(word, e)=> {
if(isAnimating && duplicates.includes(word.innerHTML) return;
if(String.fromCharCode(e. which) == word.innerHTML && !distWords.includes(word)) {
move(word)。
}
}
words.forEach(word => {
window.addEventListener("keypress"/span>, eventHandler. bind(null, word)) 。
});
問題是我無法洗掉監聽器,我使用了類似這樣的方法,但沒有成功:
我的問題是我無法洗掉監聽器。
removeIT = () =>/span> {
words.forEach(word => {
window.removeEventListener("keypress"/span>, eventHandler. bind(null, word))。
});
}
我怎樣才能有效地洗掉串列中的內容?
uj5u.com熱心網友回復:
如果你想繼續使用這種模式,你將需要存盤對每個系結函式的參考,并對它們進行迭代以移除監聽器。
const words_listeners = [] 。
words.forEach(word => {
const handler = eventHandler.bind(null, word)。
window.addEventListener("keypress"/span>, handler)。
words_listeners.push(handler)。
});
removeIT = () => {
words_listeners.forEach(handler => {
window.removeEventListener("keypress", handler)。
});
}
下面的片段是將click監聽器附加到按鈕上,所以有必要同時存盤監聽器所附加的元素,但是在你的案例中,由于你是附加到視窗上的,所以你不需要這樣。基本上,在你附加監聽器的回圈中,創建你的系結函式并將其分配給一個變數,用它附加你的監聽器,然后將其推送到一個陣列中,該陣列可用于以后移除監聽器。
const buttons = document. querySelectorAll(' .word')
const word_listeners = [];
const eventHandler = (word, e) => {
console.log(word)
}
buttons.forEach(button => {
const handler = eventHandler.bind(null, button.textContent) 。
button.addEventListener('click', handler) 。
word_listeners.push([button, handler])。
});
function remove_listeners() {
word_listeners.forEach(([button, handler]) => button。 removeEventListener('click', handler)) 。
}
document.getElementById('remov'). addEventListener('click', remove_listeners);
< button type="button" class="word" > 一</按鈕>
<button type="button" class="word">> 兩個</按鈕>
<button type="button" class="word">> 三</button>
<button type="button" id="remove">> 移除監聽器</button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
我不認為它需要那么復雜。如果你呼叫一個函式,該函式回傳一個作為監聽器的閉包,你就不需要任何系結。
我不得不在這里使用按鈕,因為我不知道你的標記是怎樣的。
。const buttons = document. querySelectorAll('button')。
function handleClick() {
console.log(this)。
}
function removeAllListeners(buttons) {
buttons.forEach(button => {
button.disabled = true。
button.removeEventListener('click', handleClick)。
});
}
function handler(word) {
console.log(word)。
return handleClick;
}
buttons.forEach(button => {
const { textContent } =按鈕。
button.addEventListener('click', handler(textContent), false) 。
});
setTimeout(removeAllListeners, 5000, buttons);
button { background-color: #efefef; cursor: pointer; }
button:disabled { background-color: #ffb3b3; cursor: default; }
< button>Tree</button>
<button>Giant</button>
<button>Billy Joel</button>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/321678.html
標籤:
