首页 > 解决方案 > 当字符串为空时,如何防止 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 并按“退格”(删除搜索输入中的最后一个符号)时,您会得到“再次失败”。有人知道使它符合条件的方法吗?感谢帮助。

标签: javascriptsearchkeyup

解决方案


当有 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"/>


推荐阅读