Javascript, key press value is always one character behind the latest?

旧城冷巷雨未停 提交于 2019-11-26 22:01:04

问题


If I type 'St', by the time I press the t, if I output the input of textfield.value in the onkeypress/onkeydown functions, I only get 'S'.

Why is this? How do I get rid of this lag?


回答1:


use the keyup event instead of keypress. keydown will show the before-keystroke value, as will keypress (apparently).




回答2:


Within the keypress event, it's still possible to prevent the typed character from registering, so the input's value canot be updated until after the keypress event. You can use the keyup event instead, or use window.setTimeout() to set up a delay.




回答3:


Because the keystroke is not registered until keyup event occurs. So you should detect onkeyup event instead of onkeypress.



来源:https://stackoverflow.com/questions/3502750/javascript-key-press-value-is-always-one-character-behind-the-latest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!