使用Jquery按下键时执行操作?

时间:2015-07-02 17:16:08

标签: jquery keypress

当我推动" 1"我想要采取行动。键盘上的键。我的代码似乎不起作用:

<script>
$(document).ready(function() {
    var code = e.keyCode || e.which;

    if (code == 97) {
        alert("hello world");
    }
});
</script>

1 个答案:

答案 0 :(得分:0)

document上使用keypress处理程序。

DEMO

$(document).ready(function() {

  $(document).on('keypress', function(e) {
    //            ^^^^^^^^
    var code = e.keyCode || e.which;
    if (code == 49) { // 1 is pressed
      alert("hello world!");
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input type="text" />