Javascript document.onkeypress 不起作用,如何解决?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10182329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:12:17  来源:igfitidea点击:

document.onkeypress is not working, how to fix?

javascript

提问by Saturnix

Is there any reason the following code should not return anything in my console log?!

以下代码是否有任何理由不应在我的控制台日志中返回任何内容?!

document.onkeypress =  zx();

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

window.onkeypressalso doesn't work.

window.onkeypress也不起作用。

Other attempts has been made, like these:

已经进行了其他尝试,例如:

document.onkeypress =  zx(event);

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

-

——

document.onkeypress =  zx;

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

Thanks!

谢谢!

回答by Starx

Omit the parenthesis on the call, you do not need to specify them.

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

Solution:

解决方案:

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

Demo

演示

回答by udidu

When attaching a functionto eventyou don't need the ()

将 a 附加functionevent您时不需要()

Just do:

做就是了:

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

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

if you are using chrome try to catch the right value by

如果您使用的是 chrome,请尝试通过以下方式捕获正确的值

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

回答by Ahmet Can Güven

Try this

尝试这个

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

This will work.

这将起作用。

回答by William Bettridge-Radford

Your function needs to define 'event'.

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

// 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 will sometimes be 0

keyCode 有时会是 0

See this page: event.keyCode on MDN

请参阅此页面:MDN 上的 event.keyCode

You probably want to use event.which

您可能想使用 event.which

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