How to know if .keyup() is a character key (jQuery)

前端 未结 7 708
遇见更好的自我
遇见更好的自我 2020-11-29 18:57

How to know if .keyup() is a character key (jQuery)

$(\"input\").keyup(function() {

if (key is a character) { //such as a b A b c 5 3 2 $ # ^ ! ^ * # ...etc         


        
7条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 19:36

    You can't do this reliably with the keyup event. If you want to know something about the character that was typed, you have to use the keypress event instead.

    The following example will work all the time in most browsers but there are some edge cases that you should be aware of. For what is in my view the definitive guide on this, see http://unixpapa.com/js/key.html.

    $("input").keypress(function(e) {
        if (e.which !== 0) {
            alert("Charcter was typed. It was: " + String.fromCharCode(e.which));
        }
    });
    

    keyup and keydown give you information about the physical key that was pressed. On standard US/UK keyboards in their standard layouts, it looks like there is a correlation between the keyCode property of these events and the character they represent. However, this is not reliable: different keyboard layouts will have different mappings.

提交回复
热议问题