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)
为什么会这样?