javascript - 当字符串为空时,如何防止 EventListener “keyup”对“backspace”做出反应?
问题描述
我正在尝试设置两个条件:
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"/>
推荐阅读
- android - onLayoutChange() 调用次数过多
- python-3.x - File.choose python 中的等价物?
- replace - Netezza,有没有办法用多个字符替换一个字符?
- python - 如何使用 boto 获取 dynamodb 表属性的空值
- menu - 在主菜单中显示前 2 个级别
- c# - appsettings-configuration 中的 Serilog PushProperty 不起作用
- javascript - 模糊内容时
模糊在内容上,但 blur 是在原始标题文本 ASP.NET JavaScript 下
- batch-file - 使用 for 循环变量调用预定义变量
- python - 无法在 Keras 中使用已加载模型与多线程环境中的 Tensorflow
- java - 重新加载 Quarkus 应用程序时,VSCode (JDWP) 不显示局部变量