document.onkeypress不工作,如何解决?

问题描述 投票:5回答:4

没有任何理由将下面的代码不应该在我的控制台日志返回什么?

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

谢谢!

javascript
4个回答
11
投票

忽略在电话会议上的括号,你不需要指定它们。

解:

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

Demo


2
投票

当附加functionevent你不需要()

做就是了:

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

1
投票

尝试这个

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

这将工作。


-1
投票

你的功能需要定义“事件”。

// 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);
}

键代码有时会0

看到这个页面:event.keyCode on MDN

你可能想使用event.which

    document.onkeypress = zx;
    function zx(event) {
        console.log(String.fromCharCode(event.which));
    }
© www.soinside.com 2019 - 2024. All rights reserved.