需要澄清有关 Javascript 的 keydown 事件和 jQuery
我有以下 jQuery 代码:
$("#someTextInputID").keydown(function(event){
console.log(event.keyCode);
console.log("input_box.val(): "+input_box.val());
console.log("input_box.val().length: "+input_box.val().length);
})
令我困惑的是,如果我输入“750”,则会记录三个 keyCode,但在输入上面的字符串后,我也在控制台中得到了这个:
input_box.val(): 75
input_box.val().length: 2
最后一个字符(即“0”)会发生什么?
I have the following jQuery code:
$("#someTextInputID").keydown(function(event){
console.log(event.keyCode);
console.log("input_box.val(): "+input_box.val());
console.log("input_box.val().length: "+input_box.val().length);
})
What puzzles me is that if I type in "750", three keyCodes are logged but I also get this in my console after having typed the string above:
input_box.val(): 75
input_box.val().length: 2
What happens then with the last character i.e. "0"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
非常简单,直到
keyup
事件发生之前,最后按下的键并不在input
的.value
中。按下按键时事件的顺序为:
keydown
(每次按键最多触发一次,key 在event.which
中可用,但在.value 中不可用
)keypress
(每次按键至少触发一次(例如,如果按住该键),key 在event.which
中可用,但在 <代码>.value)keyup
(每次按键最多触发一次,按键在event.which
中可用,和在.value
中)您可以检测按下了哪个键在
keydown
或keypress
阶段,通过检查 <Event
的 code>which 属性对象,并使用String.fromCharCode
方法。您可以使用的另一个有用技巧是使用
setTimeout
,但传递0
值作为延迟。0
的延迟会将回调添加到调用堆栈的后面,这会将执行延迟足够长的时间,以便.value
更新。:Quite simple, the last key pressed is not in the
.value
of aninput
until thekeyup
event.The order of events when pressing a key is:
keydown
(fires at most once per key press, key is available inevent.which
, but not in.value
)keypress
(fires at least once per key press (e.g. if you hold the key down), key is available inevent.which
, but not in.value
)keyup
(fires at most once per key press, key is available inevent.which
, and in.value
)You can detect which key was pressed during the
keydown
orkeypress
phase by examining thewhich
property of theEvent
object, and using theString.fromCharCode
method.Another useful trick you can employ is to use
setTimeout
, but pass a value of0
as the delay. A delay of0
adds the callback to the back of the callstack, which delays the execution long enough for the.value
to update.:用这个
Use this