admin管理员组

文章数量:1296241

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

When Ctrl+S was pressed, I don't see this myfunction is trigger. Can anyone help.? I am new to jQuery. Thanks in advance.

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

When Ctrl+S was pressed, I don't see this myfunction is trigger. Can anyone help.? I am new to jQuery. Thanks in advance.

Share Improve this question edited Sep 17, 2017 at 17:34 Fabrizio 8,0536 gold badges57 silver badges115 bronze badges asked Oct 23, 2015 at 17:41 Mark's EnemyMark's Enemy 891 silver badge8 bronze badges 2
  • 1 's' is char code 83. – Taplar Commented Oct 23, 2015 at 17:49
  • The ASCII value of 's' is 115 and hex value is 73. We need to consider the ASCII value only @Taplar What you have mentioned is hex value of 'S'. Anyway thanks – Mark's Enemy Commented Oct 24, 2015 at 8:20
Add a ment  | 

3 Answers 3

Reset to default 5

Listen for keyup and keydown. Also, the key code for 's' is 83. This reliably works:

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

function myfunction(){
    alert("Key pressed Ctrl+s");
}

Function definition is wrong:

This should work

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

As Prabhas said, your function definition was wrong.

But you'll also need to use keydown, not keypress.

Plain Javascript (which could be unreliable b/c some browsers use event.charCode and others event.keyCode):

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

jQuery (which normalises event.which for charCode and keyCode, see: http://api.jquery./event.which/):

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

本文标签: javascriptjQueryHow to trigger a function when CtrlS is pressedStack Overflow