开发者

jQuery hotkeys working for any key, not only for the designated

I added this code to my site:

$(document).bind('keydown', 'i', function(){开发者_如何学编程
$("#af").click();
return false;});

The problem is that it works with any key, not only for the 'i'. What's wrong?


In your code, 'i' is a parameter which is passed to your callback function. It has no effect on what character codes your event will respond to. You can do that via

$(document).bind('keydown', function(e){
   if (String.fromCharCode(e.keyCode) == 'I') {
      $("#af").click();
      e.preventDefault();
   }
});


Because jQuery Doc said :

event.which normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input. For more detail, read about event.charCode on the MDC.

then better to use

$(document).bind('keydown', function(e){
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 73) {   
        $("#af").click();
        return false;
    }
});


The correct way to do this is:

$(document).bind('keydown', function(e){
    if (e.keyCode =='i') {   
        $("#af").click();
        return false;
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜