jQuery键盘事件 [英] jQuery keyboard events
问题描述
使用jQuery,我想捕获一个键盘事件:
Using jQuery, I would like to capture a keyboard event that is:
- 用户举起之前
- 之后,键盘事件中的字符已在输入框中注册。
- before the user lifts their finger from the key
- after the characters from the keyboard event have registered in the input box.
要澄清,请查看此示例。触发 keypress
时,输入
值尚未更新。
To clarify, view this example. When keypress
fires, the input
value has not been updated yet.
显然我不清楚我需要什么。
Apparently I wasn't clear as to what I need.
函数必须在之前调用,然后用户从键上抬起手指,但 后,将键的字符放在输入框中。所以以下内容不起作用:
The function must be called before the user lifts their finger up from the key, but after the key's character is placed in the input box. So the following do not work:
- keydown:在
keypress
事件中,文本框中的值尚未更新 - keypress:在
keypress
事件中,文本框中的值尚未更新 - keyup:当用户抬起手指时调用此方法,这已经太晚了。
- keydown: at the
keypress
event, the value in the text box has not been updated - keypress: at the
keypress
event, the value in the text box has not been updated - keyup: this is called when the user lifts their finger, which is too late.
推荐答案
您可以使用输入
事件,该事件适用于所有主流浏览器的最新版本:
You can use the input
event, which works in recent versions of all major browsers:
var input = document.getElementById("your_input_id");
input.oninput = function() {
alert(input.value);
};
不幸的是,它在IE< = 8中不起作用。但是,在这些浏览器中你可以改为在值
属性上使用 propertychange
事件:
Unfortunately, it doesn't work in IE <= 8. However, in those browsers you can use the propertychange
event on the value
property instead:
input.onpropertychange = function() {
if (window.event.propertyName == "value") {
alert(input.value);
}
};
SO常规JavaScript回答 @ Andy E 在他的博客上详细介绍了这一点: http://whattheheadsaid.com/2011/10/update-html5-oninput-event-plugin-for-jquery
SO regular JavaScript answerer @Andy E has covered this in detail on his blog: http://whattheheadsaid.com/2011/10/update-html5-oninput-event-plugin-for-jquery
这篇关于jQuery键盘事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!