如何在jquery中获取右,左,上和下箭头键值

Bha*_*thi 5 javascript jquery javascript-events

我使用了以下代码,每当单击箭头键(左,右,上,下)时,我得到的键值为"0".有人可以帮忙吗?

 $(document).keypress(function (e) {

 alert("key value: " + e.which); 

  });
Run Code Online (Sandbox Code Playgroud)

按键时如何获得(向上,向下,向右,向左)箭头键值.

Sar*_*ath 5

使用keydowninstedkeypress

 $(document).keydown(function(event){    
    var key = event.which;                
            switch(key) {
              case 37:
                  // Key left.
                  break;
              case 38:
                  // Key up.
                  break;
              case 39:
                  // Key right.
                  break;
              case 40:
                  // Key down.
                  break;
        }   
  });
Run Code Online (Sandbox Code Playgroud)