Javascript document.onkeypress不工作,如何修复?

Javascript document.onkeypress不工作,如何修复?,javascript,Javascript,下面的代码不应该在我的控制台日志中返回任何内容,这有什么原因吗 document.onkeypress = zx(); function zx(){ console.log(event.keyCode); } // zx window.onkeypress也不起作用 还进行了其他尝试,如: document.onkeypress = zx(event); function zx(event){ console.log(event.keyCode); } // zx -

下面的代码不应该在我的控制台日志中返回任何内容,这有什么原因吗

document.onkeypress =  zx();

function zx(){
    console.log(event.keyCode);
} // zx
window.onkeypress
也不起作用

还进行了其他尝试,如:

document.onkeypress =  zx(event);

function zx(event){
    console.log(event.keyCode);
} // zx
-


谢谢

省略调用中的括号,您不需要指定它们

解决方案:

document.onkeypress =  zx;
function zx(e){
    var charCode = (typeof e.which == "number") ? e.which : e.keyCode
    console.log(charCode);
}

函数
附加到
事件
时,不需要
()

只要做:

document.onkeypress =  zx; //note! don't use the ()

function zx(){
    console.log(event.keyCode);
} // zx
如果您使用的是chrome,请尝试通过

function zx(e){
    var key = e.which || e.keyCode;
    console.log(key);
} // zx
试试这个

document.onkeypress = displayunicode;
function displayunicode(event){
    var charCode = (typeof event.which == "number") ? event.which : event.keyCode
    console.log(charCode )
}

这将起作用。

您的函数需要定义“事件”

// assign a reference to zx; but don't call zx
document.onkeypress =  zx;

// event needs to be defined
function zx(event){
    console.log(event.keyCode);
}
keyCode有时为0

见本页:

您可能想使用event.which

    document.onkeypress = zx;
    function zx(event) {
        console.log(String.fromCharCode(event.which));
    }

已经完成了,但仍然不起作用。当我按下鼠标时,我的控制台上只有“0”,但当我按下按键时,什么都没有。@Saturnix,我被制作成了一个演示。检查它们如果你看到我的第三次尝试,你会看到我已经尝试过了,但仍然不起作用:(无论如何,谢谢!你的第三次尝试在函数定义中缺少事件的定义。另外,keyCode没有做你认为它做的事情:阅读notes部分。
console.log(String.fromCharCode(event.which));
并不能给出正确的结果。当您在
event.which==40
时执行此操作时,会得到“(”。但40是向下箭头。
    document.onkeypress = zx;
    function zx(event) {
        console.log(String.fromCharCode(event.which));
    }