简体   繁体   中英

Unwanted event handler function is executing in jQuery

I'm new to jQuery and I've some problem of redundant execution of an event handler. Here is my code:

$(document).bind('keydown', 'ctrl+c', function(){
    console.log("Something is wrong!!!");
});

I'm not pressing, Ctrl+C at all, but my console is printing the message as many times as I'm pressing any key. What's the flaw here? Thanks in advance, for any assistance.

You're binding the event to ANY keydown . You want to use the keydown event, but then check to make sure that your specified keys are the ones being pressed. e.ctrlKey will check for Ctrl , and you can use e.which to compare the other key, which in this case would be C

Here's a full example

$(document).bind('keydown', function(e) {
  console.log('some key pressed');
  if (String.fromCharCode(e.which).toLowerCase() == "c" && e.ctrlKey) {
    alert('ctrl+C pressed');
  }
});

According to the API , you're passing 'ctrl+c' to the event handler as event data, which means that the callback will execute on every keydown event and you're not making use of the 'ctrl+c' data you passed in to do any key checking.

If, instead, what you want is to detect when a key is pressed in combination with ctrl you'll need to check the which and ctrlKey properties of the event object:

...keydown(function (e) {
    if (e.which === yourkeycode && e.ctrlKey) {
        ...do stuff...
    }
});

Andrew's answer is correct, however JQuery offers binding to copy/paste/cut actions directly, which is cleaner.

$(document).bind('copy', function() {
  alert('ctrl+C pressed');
}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM