如何防止事件侦听器"keyup"在字符串为空时对"退格"做出反应?



我正在尝试设置 2 个条件:

userInput = document.getElementById("search")
userInput.addEventListener("keyup", (e) => {
if ((e.target.value).length === 0 && e.keyCode === 8) {
console.log("Fail again");
} 
})

。而且一开始工作正常。但是当 string.length === 1 并按"退格键"(删除搜索输入中的最后一个符号(时,你会得到"再次失败"。 有没有人知道某种方法可以使其遵循条件?感谢您的帮助。

当有 1 个字符并按退格键时,输入值将更改(空(,然后触发keyup事件。您的条件已满足,因此您会看到该消息。如果想知道退格键生效之前的值是多少,请使用keydown

演示:

userInput = document.getElementById("search")
userInput.addEventListener("keydown", (e) => {
if (e.target.value.length === 0 && e.keyCode === 8) {
console.log("Fail again");
} 
})
<input id="search"/>

如果仍然希望能够在事件侦听器中获取更新的值,可以执行以下操作:

const userInput = document.getElementById("search");
let previousSearchValue = userInput.value;
userInput.addEventListener("keyup", (e) => {
if (previousSearchValue.length === 0 && e.keyCode === 8) {
console.log("Fail again");
}
previousSearchValue = e.target.value;
});
<input id="search"/>

最新更新