我想將按鍵事件監聽器附加到每個 words dom 元素上,并將元素本身(我指的是 word)傳遞給 eventHandler ok?
所以我試著這樣做,但似乎我失去了事件本身:
const eventHandler=(e, word)=> {
console.log('keypressed', String。 fromCharCode(e.which), word)。)
}
words.forEach((word) =>/span> {
window.addEventListener("keypress", eventHandler.bind(event, word))。
});
String.fromCharCode(e.which)應該帶來鍵盤上的按下的鍵,但它什么也沒有回傳!!
我怎樣才能解決這個問題呢?
編輯:
下面是這個問題的簡單再現:按下鍵盤上的任何一個鍵,看到事件是未定義的:
。const eventHandler=(event, word)=> {
console.log('keypressed'/span>, event, word)。
}
window.addEventListener("keypress", eventHandler. bind(this, event, 'word'));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
事件是隱式傳遞的,它將是所有系結引數之后的最后一個引數。
所以你會使用eventHandler.bind(null, word),然后處理程式應該被宣告eventHandler(word, e) {...}
const button = document. getElementById('b'/span>)。
function handler(bound_arg, event) {
console.log(event.target)。
console.log(bound_arg)。
}
button.addEventListener('click'/span>, handler. bind(null,'bound'));
< button type='button' id='b'> Bound</button>。
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
但這不是很直觀,由于bind()無論如何都會創建一個新的函式,你可以簡單地使用一個匿名函式來傳遞這個詞。
window。 addEventListener("keypress", (e) => eventHandler(e, word))。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/321679.html
標籤:
上一篇:移除帶有額外引數的事件監聽器
