没有任何理由将下面的代码不应该在我的控制台日志返回什么?
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
谢谢!
忽略在电话会议上的括号,你不需要指定它们。
解:
document.onkeypress = zx;
function zx(e){
var charCode = (typeof e.which == "number") ? e.which : e.keyCode
console.log(charCode);
}
当附加function
到event
你不需要()
做就是了:
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);
}
键代码有时会0
看到这个页面:event.keyCode on MDN
你可能想使用event.which
document.onkeypress = zx;
function zx(event) {
console.log(String.fromCharCode(event.which));
}