jQuery Event Keypress: Which key was pressed?

后端 未结 24 2080
半阙折子戏
半阙折子戏 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:09

    edit: This only works for IE...

    I realize this is an old posting, but someone might find this useful.

    The key events are mapped, so instead of using the keycode value you can also use the key value to make it a little more readable.

    $(document).ready( function() {
        $('#searchbox input').keydown(function(e)
        {
         setTimeout(function ()
         { 
           //rather than using keyup, you can use keydown to capture 
           //the input as it's being typed.
           //You may need to use a timeout in order to allow the input to be updated
         }, 5);
        }); 
        if(e.key == "Enter")
        {
           //Enter key was pressed, do stuff
        }else if(e.key == "Spacebar")
        {
           //Spacebar was pressed, do stuff
        }
    });
    

    Here is a cheat sheet with the mapped keys which I got from this blog enter image description here

提交回复
热议问题