第一次触发事件时,按键事件不会记录输入值

时间:2019-05-22 03:30:36

标签: javascript settimeout onkeypress

此事件首次触发时,即使输入具有值,它也会记录为空。它第二次记录该值,但落后一步。

document.addEventListener('DOMContentLoaded', () => {
  const input = document.querySelector('input');
  input.addEventListener('keypress', e => {
    console.log(e.target.value);
  });
});
<input type="text" />

即使我过去了0毫秒,这也可以使它工作。

document.addEventListener('DOMContentLoaded', () => {
  const input = document.querySelector('input');
  input.addEventListener('keypress', e => {
    setTimeout(() => console.log(e.target.value), 0);
  });
});
<input type="text" />

那是为什么?

5 个答案:

答案 0 :(得分:3)

当您第一次在输入上按下key时,在发生empty事件时,分配给该输入的值为keypress ,然后将该字符添加到输入中。这对于以后的keypress事件有效,您读取的input的值是input更改之前的值。另外,如果您在MDN上进行阅读,则会出现有关keypress掉落的警告。您可能想改听keyup事件:

const input = document.querySelector('input');

input.addEventListener('keyup', e => {
    console.log(e.target.value);
});
.as-console {background-color:black !important; color:lime;}
<input type="text" id="input">

答案 1 :(得分:2)

keypress事件不会更改输入value-您读取的是“旧”值-当前键在e.key

document.addEventListener('DOMContentLoaded', () => {
  const input = document.querySelector('input');
  input.addEventListener('keypress', e => {
    console.log('value',e.target.value);
    console.log('key',e.key);
  });
});
<input>

您可以使用onkeyup事件在event.target.value中获得当前值

document.addEventListener('DOMContentLoaded', () => {
  const input = document.querySelector('input');
  input.addEventListener('keyup', e => {
    console.log('value', e.target.value);
    console.log('key', e.key);
  });
});
<input>

将在执行setTimeout函数之前更新输入值(即使持续0 ms)-关键字:js event loop

答案 2 :(得分:1)

根据jQuery docs

  

当浏览器注册时,keypress事件发送到一个元素   键盘输入。这类似于keydown事件,除了   修改键和非打印键,例如Shift,Esc和Delete触发器   按键事件,但不包括按键事件。之间的其他差异   根据平台和浏览器,可能会发生两个事件。

     

当用户释放按键时,会将keyup事件发送到元素   键盘。

     

oninput事件是一个在输入时触发的事件   变化。

因此% Copyright 1993-2016 The MathWorks, Inc. 将在值更改前被触发,请改用keypress

关于keyup,当您将代码放在该位置时,它将是异步功能(即使持续0 ms)。在javascript中,所有同步命令完成后,将执行异步功能

答案 3 :(得分:0)

那是因为在更新输入值之前将其触发。您可以尝试使用keyUp代替keyPress

答案 4 :(得分:0)

释放键时会触发keyup事件,这会产生一点延迟的感觉。我宁愿使用keydown事件,该事件的行为与OP公开的行为相同。 (请注意,keypress事件现在为deprecated

您无需等待下一个刻度(通过使用setTimeout),就可以将当前值与按下的键连接起来:

document.addEventListener('DOMContentLoaded', () => {
  const input = document.getElementById('input');

  input.addEventListener('keydown', event => {
    console.log(event.target.value + event.key);
  });
});
<input type="text" id="input">

编辑:再尝试一点此解决方案后,在输入文本之间移动光标或到达maxlength时,它无法按预期工作,所以我终于结束了使用OP提出的setTimeout和超时为0的解决方法

相关问题