按键动作

Moh*_*eri 5 javascript jquery onkeypress

我正在设计一个基于Web的会计软件。例如,每当用户按下N键时,我都想打开“新会计凭证” 。只要他/她按下S键,就打开“设置” 。

我看到了一些基于JavaScript和jQuery的脚本。但是它们并没有完全起作用。有人可以帮我吗?

我已经尝试过以下脚本:

var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) { //Enter keycode
   //Do something
}
Run Code Online (Sandbox Code Playgroud)

Tho*_*son 6

$(document).bind('keyup', function(e){
    if(e.which==78) {
      // "n"
    }
    if(e.which==83) {
      // "s"
    }
});
Run Code Online (Sandbox Code Playgroud)

为了防止输入是否集中:

$("body").on("focus",":input", function(){ $(document).unbind('keyup'); });
$("body").on("blur",":input", function(){ $(document).bind('keyup', function(e){ etc.... });
Run Code Online (Sandbox Code Playgroud)

您可能希望将bind函数放入自己的函数中,这样就不会重复代码。例如:

function bindKeyup(){
    $(document).bind('keyup', function(e){
      if(e.which==78) {
        // "n"
      }
      if(e.which==83) {
        // "s"
      }
    });
}
$("body").on("focus",":input", function(){ $(document).unbind('keyup'); });
$("body").on("blur",":input", function(){ bindKeyup(); });
Run Code Online (Sandbox Code Playgroud)