如何在按下Ctrl + S时触发一个函数

jQuery - How to trigger a function when Ctrl + S is pressed?

本文关键字:函数 一个 Ctrl      更新时间:2023-09-26
   $(window).keypress(function(event) {
    if (event.which == 115 && event.ctrlKey){
        myfunction();
    }
   });
   myfunction(){
    alert("Key pressed Ctrl+s");
   }

Ctrl+S被按下时,我没有看到这个myfunction是触发器。有人能帮忙吗?我是新的jQuery

监听keyupkeydown。另外,"s"的键码是83。

$(document).bind("keyup keydown", function(e){
    if(e.ctrlKey && e.which == 83){
        myfunction();
    }
});
function myfunction(){
    alert("Key pressed Ctrl+s");
}

函数定义错误:

应该可以

$(window).keypress(function(event) {
  if (event.which == 115 && event.ctrlKey){
    myfunction();
    return false;
  }
});
function myfunction(){
    alert("Key pressed Ctrl+s");
}

正如Prabhas所说,你的函数定义是错误的。

但是你也需要使用keydown,而不是keypress

纯Javascript(可能不可靠,因为有些浏览器使用event.charCode和其他event.keyCode):

  window.addEventListener('keydown', function(e) {
        if (e.keyCode == 83 && event.ctrlKey) {
          myfunction();
        }
    });

jQuery(将event.which规范化为charCodekeyCode,参见:http://api.jquery.com/event.which/):

$(document).bind("keydown", function(e) {
    if(e.which == 83 && event.ctrlKey){
        myfunction();
    }
});