【发布时间】:2017-05-13 17:50:28
【问题描述】:
我想要它,所以当按下向上或向下键时,它会触发不同的功能。到目前为止,这是我的代码:
window.addEventListener('keypress', function(e) {
console.log("A Key has been pressed");
/*Sets "key" variable to be the value of the key code of the key pressed*/
var key = e.which || e.keyCode;
/*checks if key pressed is the "up" key*/
if (key === 38){
functionOne();
console.log("Up key was Pressed");
}
/*checks if key pressed is the "down" key*/
else if (key === 40){
functionTwo();
console.log("Down key was Pressed");
}
})
每当我按下除箭头键、shift、alt、caps、tab 和 f1 - f12 之外的任何键时,都会激活控制台日志,显示“已按下一个键”。这可能是什么原因造成的?
先谢谢你了。
【问题讨论】:
-
您如何验证事件正在触发?在事件回调本身中放置一个 console.log - 永远不要假设它正在触发。如果是,下一步是检查
key的值是多少。基本调试。 -
谢谢你的好建议,我会根据结果添加并编辑问题。
-
你用什么浏览器来测试这个?
-
Chrome 网络浏览器
标签: javascript function if-statement addeventlistener keycode