keypress 事件不会在第一次触发事件时记录输入值

Joh*_*now 6 javascript onkeypress settimeout

keypress事件第一次触发时,即使输入有值,它也会记录一个空的输入值。它第二次记录该值,但与输入值相比,它落后了一个键击。您可以在下一个示例中检查此行为:

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

    input.addEventListener('keypress', e =>
    {
        console.log(e.target.value);
    });
});
Run Code Online (Sandbox Code Playgroud)
<input type="text"/>
Run Code Online (Sandbox Code Playgroud)

但是,下一个解决方法使它起作用,即使我传入0ms.

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

    input.addEventListener('keypress', e =>
    {
        setTimeout(() => console.log(e.target.value), 0);
    });
});
Run Code Online (Sandbox Code Playgroud)
<input type="text"/>
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

Shi*_*rsz 9

当您key第一次按 a时,分配给输入的值是emptykeypress事件发生时,然后将字符添加到输入中,但稍后。这同样适用于未来的keypress事件,input您读取的值是input changes. 此外,如果您在MDN上阅读,会有关于按键被删除的警告。因此,您可能希望监听keyup事件,如下例所示:

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

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