试图从按键文档获取数字,javascript

试图从按键文档获取数字,javascript,javascript,jquery,Javascript,Jquery,这看起来很简单,但我不知道如何从文档DOM截取javascript上的数字 $(document).keypress(function (e) { if (e.keyCode == xx) { alert(); } }); $document.keydownfunctionevent{ ifevent.keyCode==13{ 警告“您按enter键了”;} }; 将13替换为钥匙代码,详情请参见此处: $document

这看起来很简单,但我不知道如何从文档DOM截取javascript上的数字

    $(document).keypress(function (e) {
        if (e.keyCode == xx) {
            alert();
        }
    });
$document.keydownfunctionevent{ ifevent.keyCode==13{ 警告“您按enter键了”;} }; 将13替换为钥匙代码,详情请参见此处: $document.keydownfunctionevent{ ifevent.keyCode==13{ 警告“您按enter键了”;} }; 将13替换为钥匙代码,详情请参见此处:
数字是48到57,所以

$(document).keypress(function (e) {
    var key = e.keyCode || e.charCode;
    if (key >= 48 && key <= 57) {
        alert('You pressed ' + (key - 48));
    }
});

数字是48到57,所以

$(document).keypress(function (e) {
    var key = e.keyCode || e.charCode;
    if (key >= 48 && key <= 57) {
        alert('You pressed ' + (key - 48));
    }
});
资料来源:

Keypress事件在Firefox中生成一个0的键码,在其他地方生成ASCII字符值。按键事件在Firefox中产生ASCII字符值的字符码。因此,应该使用e.keyCode | | e.charCode来获取字符值

还要注意,您的代码也无法工作,因为alert应该接受一个参数。至少在Firefox中,在没有参数的情况下调用alert会引发异常

修复这两个问题后,您的代码现在将是:

$(document).keypress(function (e) {
    if ((e.keyCode || e.charCode) == <number from 48..57 inclusive>) {
        alert('something');
    }
});
示例:

来源:

Keypress事件在Firefox中生成一个0的键码,在其他地方生成ASCII字符值。按键事件在Firefox中产生ASCII字符值的字符码。因此,应该使用e.keyCode | | e.charCode来获取字符值

还要注意,您的代码也无法工作,因为alert应该接受一个参数。至少在Firefox中,在没有参数的情况下调用alert会引发异常

修复这两个问题后,您的代码现在将是:

$(document).keypress(function (e) {
    if ((e.keyCode || e.charCode) == <number from 48..57 inclusive>) {
        alert('something');
    }
});
例如:

您应该注意到事件[keyCode,charCode,which]之间的差异 这个测试页面受浏览器的影响,即我在safari上测试了它 onKeyPress总是空的

您应该注意到事件[keyCode,charCode,which]之间的差异 这个测试页面受浏览器的影响,即我在safari上测试了它 onKeyPress总是空的


它在Firefox中不起作用,因为对于keypress,您需要在Firefox中使用charCode。在Firefox中,keyCode始终为零。它在Firefox中不起作用,因为对于keypress,您需要在Firefox中使用charCode。在Firefox中,keyCode始终为零。