3

I want to use hotkeys in one of my pages. However, it seems that the only key that can be detected in my hotkeys is the Enter Key.

$(document).keypress(function(e) {
    var key = e.which;
    switch (key)
    {
        case 72:
          alert("H");
          break;
        case 82:
          alert("R");
          break;
        case 66:
          alert("B");
          break;
        case 13:
          alert("ENTER");
          break;
        default:
          alert("Invalid");
    }
});

Reference of key code values: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

4

1 回答 1

5

According to MDN (via the jQuery docs for event.which), e.which returns Unicode character codes, so H could be either 72 or 104 (h) depending on text case.

In a keypress event, the Unicode value of the key pressed is stored in either the keyCode or charCode property

Example fiddle

于 2013-09-18T12:45:35.997 回答