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

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

本文介绍了keypress 事件不会在第一次触发事件时记录输入值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The first time a keypress event fires, it logs an empty input value even though the input has a value. The second time it logs the value but is one keystroke behind in comparison with the input's value. You can check this behavior on the next example:

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

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

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

However, the next workaround makes it work, even though I pass in 0ms.

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

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

为什么会这样?

推荐答案

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

When you press a key for the first time, the value assigned to the input is empty at the time the keypress event takes place, then the character is added to the input, but a moment later. This same is valid for future keypress events, the value of the input you read is the previous before the input changes. Also, if you read on the MDN there is a warning about keypress being dropped. Hence, and instead, you may want to listen on keyup event as shown on the next example:

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">

这篇关于keypress 事件不会在第一次触发事件时记录输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 08:58