Lee*_*lla 11 javascript keycode
我试图用以下代码从数字键盘解析keydown事件:
$('#myDiv').keydown(function(e) {
val = String.fromCharCode(e.which)
});
Run Code Online (Sandbox Code Playgroud)
问题是键盘0-9
返回keyCodes 96-105
,根据fromCharCode()
小写字母a-i
.如何将numberpad的keydown事件解析为适当的数字?
Tim*_*own 21
你没有:你使用这个keypress
事件.该keypress
事件是唯一可以为您提供有关键入字符的可靠信息的事件.如果您只是更改keydown
为,现有代码将起作用keypress
.
which
传递给的值keydown
不是字符代码; 它是一个关键代码(代码从浏览器/操作系统到浏览器/操作系统不等).你可以使用这个页面上的表格将它映射到一个角色,但是要说这些东西有点......尴尬...会低估这种情况.:-)
否则,最好的办法是等待keypress
事件,该事件将包含字符代码(如果相关)而不是密钥代码.
jQuery(function($) {
$("#theField")
.keydown(function(event) {
showKey("keydown", event.which);
})
.keypress(function(event) {
showKey("keypress", event.which);
})
.focus();
function showKey(eventName, which) {
display(eventName +
": " + which + " (" +
String.fromCharCode(which) + ")");
}
function display(msg) {
$("<p>").html(msg).appendTo(document.body);
}
});
Run Code Online (Sandbox Code Playgroud)
使用此HTML:
<input type="text" id="theField">
Run Code Online (Sandbox Code Playgroud)