看起来很简单,但我无法想象如何拦截来自Document DOM的javascript上的数字
$(document).keypress(function (e) {
if (e.keyCode == xx) {
alert();
}
});
答案 0 :(得分:5)
数字是48到57,所以......
$(document).keypress(function (e) {
var key = e.keyCode || e.charCode;
if (key >= 48 && key <= 57) {
alert('You pressed ' + (key - 48));
}
});
答案 1 :(得分:1)
来源:http://www.quirksmode.org/js/keys.html
Keypress事件在Firefox中产生一个0的keyCode,在其他地方产生ASCII字符值。 Keypress事件在Firefox中生成ASCII字符值的charCode。因此,您应该使用(e.keyCode || e.charCode)
来获取字符值。
另请注意,您的代码也无效,因为alert
应该接受一个参数。至少在Firefox中,没有参数调用alert
会引发异常。
修复这两个问题后,您的代码现在将是:
$(document).keypress(function (e) {
if ((e.keyCode || e.charCode) == <number from 48..57 inclusive>) {
alert('something');
}
});
答案 2 :(得分:0)
$(document).keydown(function(event){
if(event.keyCode == 13) {
alert('you pressed enter');}
});
使用密钥代码替换13,有关详细信息,请参阅此处:
http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
答案 3 :(得分:0)
您应该注意事件 [keyCode,charCode,which] 之间的差异 这个测试页面受浏览器的影响,我在 safari 上测试了它 onKeyPress 始终为空