jQuery Event Keypress: Which key was pressed?

后端 未结 24 2715
半阙折子戏
半阙折子戏 2020-11-21 16:48

With jQuery, how do I find out which key was pressed when I bind to the keypress event?

$(\'#searchbox input\').bind(\'keypress\', function(e) {});
         


        
24条回答
  •  天命终不由人
    2020-11-21 17:08

    If you are using jQuery UI you have translations for common key codes. In ui/ui/ui.core.js:

    $.ui.keyCode = { 
        ...
        ENTER: 13, 
        ...
    };
    

    There's also some translations in tests/simulate/jquery.simulate.js but I could not find any in the core JS library. Mind you, I merely grep'ed the sources. Maybe there is some other way to get rid of these magic numbers.

    You can also make use of String.charCodeAt and .fromCharCode:

    >>> String.charCodeAt('\r') == 13
    true
    >>> String.fromCharCode(13) == '\r'
    true
    

提交回复
热议问题