You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中如何在keydown事件中获取输入值?

解决keydown事件中获取输入框实时值的问题

keydown事件触发时,浏览器还没把输入的字符更新到输入框的value属性里,所以你拿到的是输入前的旧值,弹窗自然为空。下面是几种可行的解决办法:

方案1:改用keyup事件

keyup在按键松开时触发,此时字符已经写入输入框,能直接获取最新值:

<input type="text" id="name" onkeyup="myFunction()">

<script>
  function myFunction() {
    var name = document.getElementById("name").value;
    alert(name);
  }
</script>

方案2:在keydown中延迟获取

用setTimeout把获取值的操作延后,哪怕延迟0毫秒,也能等浏览器更新完输入框value再执行:

<input type="text" id="name" onkeydown="myFunction()">

<script>
  function myFunction() {
    setTimeout(() => {
      var name = document.getElementById("name").value;
      alert(name);
    }, 0);
  }
</script>

方案3:通过事件对象拼接字符

如果必须用keydown,可以通过event.key拿到当前按键的字符,和输入框原有值拼接得到最新值(需处理退格等特殊按键):

<input type="text" id="name" onkeydown="myFunction(event)">

<script>
  function myFunction(e) {
    let input = document.getElementById("name");
    let currentValue = input.value;
    let newValue = currentValue;

    if (e.key === "Backspace") {
      // 退格键删除最后一个字符
      newValue = currentValue.slice(0, -1);
    } else if (e.key.length === 1) {
      // 只处理可打印的单个字符
      newValue = currentValue + e.key;
    }
    // 其他特殊按键(比如方向键)保持原有值

    alert(newValue);
  }
</script>

内容的提问来源于stack exchange,提问作者Henry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 06:50:27