我使用 jQuery 来处理按键事件。这是我的命令:
$(document).ready(function() {
$(document).bind('keydown', 'f1', function() {
alert('f1');
});
});
$(document).ready(function() {
$(document).bind('keydown', 'f2', function() {
alert('f2');
});
});
我想当我按下 F1 键时,我会得到一个 alert('f1')
并且当我按下 >kbd>F2 键时,我会得到一个 警报('f2')
但是当我按下 F1 键时,我得到 2 alert('f1')
。
当我按下 F1 键时,如何获得 alert('f1')
?
最佳答案
如果您想要立即 react ,这是您的最佳选择:
http://jsfiddle.net/sZmST/18/
$(document).keypress(function(k) {
switch(k.keyCode){
// user presses the "F1"
case 112: alert("F1");
break;
// user presses the "F2"
case 113: alert("F2");
break;
}
});
为了演示 JS-Fiddle,我提供了映射 keyCode
s 的工作演示:
HTML:
<input id="whichkey" value="play_here"><span>This will tell you char_code</span>
<p>Click into our body and press F1 or F2. Problem solved.
Javascript(完整):
$("#whichkey").on("keydown", function(e) {
alert(e.which);
});
$(document).keypress(function(k) {
console.log(k.keyCode);
switch(k.keyCode)
{
// user presses the "F1"
case 112: alert("F1");
break;
// user presses the "F2"
case 113: alert("F2");
break;
}
});
再一次,在这里查看。这会更有意义:
http://jsfiddle.net/sZmST/18/
我觉得您正在尝试扩展它,所以我为您提供了一个解决方案,您可以使用它来实现。我在许多 JavaScript 游戏中都将其用作核心功能
,最好始终考虑可扩展性。
任何人都可以golf code(让它尽可能快速和最短地运行),但除非它有一个 100% 的特定任务,否则你会更好地考虑你的function
可以做到。
关于javascript - jQuery 中的按键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22624692/