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
document.onkeypress is not working, how to fix?
提问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.onkeypress
also 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
回答by udidu
When attaching a function
to event
you don't need the ()
将 a 附加function
到event
您时不需要()
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));
}