removeEventListener 未在 'keydown' 事件上执行



我有一个面板站点,用户可以在其中按"键在列表视图或网格视图之间切换;l〃;或";g";热键在站点窗口的任何位置。由于这个eventListener是在整个窗口的"keydown"事件上调用的,这导致了这样一个问题,即如果用户输入";l〃;或";g";在网站上的搜索文本框中键入时。

为了缓解这个问题,我的方法是在"keydown"元素的搜索文本框元素上添加一个eventListener,它将删除window元素上"keydown"的eventListener。然后,我实现了一个计时器,在用户停止键入后开始倒计时3秒(通过在"keyup"事件的搜索文本框中添加eventListener(。

在搜索文本框上没有触发"keydown"事件的情况下,经过3秒钟后,我再次将"keydown"eventListener添加回窗口元素。

JS代码

let timer;
let timeInterval = 3000; // milliseconds so equates to 3 seconds
let searchTextBox = document.querySelector("#search-textbox");
if (typeof (searchTextBox) != 'undefined' && searchTextBox != null) { // check if the search text box was successfully created and inserted into the DOM
searchTextBox.addEventListener('keydown', function () { // when key is pressed on the search text box, remove the window eventListener
window.removeEventListener('keydown', addViewHotKeys);
});
searchTextBox.addEventListener('keyup', function () { // start the timer after a key is released
console.log('key lifted');
clearTimeout(timer); // clear the timeout if it was already set
if (searchTextBox.value) { // if the textbox has any input inside, set the timer to execute the finishedTyping function after the timeInterval milliseconds has elapsed
timer = setTimeout(finishedTyping, timeInterval);
}
});
function finishedTyping() {
addViewHotKeys();
console.log('times up');
}
}
// Detect hotkeys for easy navigation on index.html
function addViewHotKeys() {
window.addEventListener('keydown', function (event) {
if (event.key === 'l') {
if (state.display !== 'list') {
state.display = 'list';
renderViewSelection();
renderDashboardPlane();
}
} else if (event.key === 'g') {
if (state.display !== 'grid') {
state.display = 'grid';
renderViewSelection();
renderDashboardPlane();
}
}
});
}
window.addEventListener('load', function () {
addViewHotKeys();
});

我在搜索textBox上的"keydown"one_answers"keyup"事件监听器成功触发(计时器在3秒后执行finishedType函数,按预期工作(。然而,对于搜索框上的"keydown"eventListener,它并没有删除window元素上的eventListener。我仍然找不到为什么会出现这种情况的原因。

解决这个问题的一个更干净的方法可能是使用搜索文本框焦点和模糊事件,而不是在键输入上使用计时器。

以下示例在您关注输入元素时删除keydown事件侦听器,并在输入元素失去焦点时再次添加它。您可以应用相同的技术来包括任何其他输入元素。

let searchTextBox = document.querySelector("#search-textbox");
// Detect hotkeys for easy navigation on index.html
function addViewHotKeys(event) {
if (event.key === 'l') {
console.log('l');

// useful code here

} else if (event.key === 'g') {
console.log('g');

// useful code here
}
}
window.addEventListener('load', function () {
searchTextBox.addEventListener('focus', function() {
window.removeEventListener('keydown', addViewHotKeys);
});

searchTextBox.addEventListener('blur', function() {
window.addEventListener('keydown', addViewHotKeys);
});

window.addEventListener('keydown', addViewHotKeys);
});
<p>Press the l or g key to log that letter to the console, except when the input has focus:</p>
<input id="search-textbox" type="search" value="" placeholder="search-textbox" />

最新更新