js onkeypress 在下一个输入之前不起作用

mah*_*sif 5 javascript

当输入大小恰好为 2 时,我尝试插入连字符。这是我的代码

document.getElementById('numberInput').onkeypress = function() {
  if (this.value.length == 2) {
    this.value = this.value + '-';
  }
}
Run Code Online (Sandbox Code Playgroud)
<input type="text" id="numberInput">
Run Code Online (Sandbox Code Playgroud)

但问题是 - 直到输入第三个字符才出现。尽管连字符放置正确,但我的意思是在两个字符之后。

输入两个字符后如何立即得到连字符?

我尝试过onkeyup,但问题是当我按退格按钮时它也会触发。当有两个字符时,会出现连字符,但此时如果我按退格键并删除连字符,它会立即返回。所以我选择onkeypress

Nes*_*oro 3

onKeyPress 期间输入文本框的值始终为更改前的值。这允许事件侦听器取消按键。

要在字段值更新后获取值,请安排一个函数在下一个事件循环上运行。通常的方法是调用 setTimeout 并将超时设置为 0:

document.getElementById('numberInput').onkeypress = function() {
  // arrow function keeps scope
  setTimeout(() => {
    // now it is the value after the keypress
    if (this.value.length == 2) {
      this.value = this.value + '-';
    }
  }, 0);
}
Run Code Online (Sandbox Code Playgroud)
<input type="text" id="numberInput">
Run Code Online (Sandbox Code Playgroud)