所以问题是...它不起作用。而且更正确地...我该如何更好地执行这些嵌套的if
?
document.body.onkeypress = function(e) {
e = e || window.event;
if (e.keyCode == '38') { //arrow up
}
if (e.keyCode == '40') { //arrow down
if (top == 1) {
window.setTimeout(show2, 100);
alert('2 layer works');
}
if (top == 2) {
window.setTimeout(show3, 100);
}
if (top == 3) {
window.setTimeout(show4, 100);
}
}
}
我已经尝试了一切。请帮助我...
答案 0 :(得分:0)
从此示例开始。它显示了如何正确地将keydown事件连接到文档主体。从这里,您应该可以对其进行修改,以添加示例中具有的其他逻辑。请务必确保正确设置了top
之类的外部变量。
function handleKeyDown(e) {
console.log('got keyDown event. e.keyCode =', e.keyCode)
}
document.body.addEventListener("keydown", handleKeyDown, false);
<p>Press a key</p>
答案 1 :(得分:0)
您在哪里更改top
的值...?同样,第一个if语句(如果它像您在此处显示的那样空白)将引发错误,或者至少不会执行任何操作。你为什么说e = e || window.event
..?同样,这可能只是我,但不要调用此类函数。更好(至少在我看来也是):
document.body.addEventListener("keypress", e => {
// Get rid of that e = e || window.event, I have no clue why you'd do that.
if (e.keyCode == 38) {
// Actually give it some parameters to do here, leaving it empty will either
// throw an error or in "best" case won't do anything.
}
if (e.keyCode == 40) {
// Again, you said you did var top = 1. It will work here.
if (top == 1) {
window.setTimeout(show2, 100);
alert('2 layer works');
}
// But you dont INCREMENT the top variable anywhere, so this wont work.
if (top == 2) {
window.setTimeout(show3, 100);
}
// But you dont INCREMENT the top variable anywhere, so this wont work.
if (top == 3) {
window.setTimeout(show4, 100);
}
}
})
这个问题的格式确实非常错误,您没有提供太多信息。向我们显示您收到的错误,请始终使用console.log
,这是您最好的朋友。