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

前端 未结 7 706
遇见更好的自我
遇见更好的自我 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:33

    I'm not totally satisfied with the other answers given. They've all got some kind of flaw to them.

    Using keyPress with event.which is unreliable because you can't catch a backspace or a delete (as mentioned by Tarl). Using keyDown (as in Niva's and Tarl's answers) is a bit better, but the solution is flawed because it attempts to use event.keyCode with String.fromCharCode() (keyCode and charCode are not the same!).

    However, what we DO have with the keydown or keyup event is the actual key that was pressed (event.key). As far as I can tell, any key with a length of 1 is a character (number or letter) regardless of which language keyboard you're using. Please correct me if that's not true!

    Then there's that very long answer from asdf. That might work perfectly, but it seems like overkill.


    So here's a simple solution that will catch all characters, backspace, and delete. (Note: either keyup or keydown will work here, but keypress will not)

    $("input").keydown(function(event) {
    
        var isWordCharacter = event.key.length === 1;
        var isBackspaceOrDelete = event.keyCode === 8 || event.keyCode === 46;
    
        if (isWordCharacter || isBackspaceOrDelete) {
            // do something
        }
    });
    

提交回复
热议问题