如何知道.keyup()是否是一个字符键(jQuery)

时间:2010-10-20 12:16:02

标签: javascript jquery events keyboard keycode

如何知道.keyup()是否是字符键(jQuery)

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

if (key is a character) { //such as a b A b c 5 3 2 $ # ^ ! ^ * # ...etc not enter key or shift or Esc or space ...etc
/* Do stuff */
}

});

7 个答案:

答案 0 :(得分:99)

keyup事件无法可靠地执行此操作。 如果您想了解有关输入字符的信息,则必须使用keypress事件。

以下示例将在大多数浏览器中始终有效,但您应该注意一些边缘情况。有关这方面的权威指南,请参阅http://unixpapa.com/js/key.html

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

keyupkeydown为您提供有关已按下的物理键的信息。在标准布局中的标准美国/英国键盘上,看起来这些事件的keyCode属性与它们所代表的角色之间存在关联。但是,这不可靠:不同的键盘布局会有不同的映射。

答案 1 :(得分:45)

注意:事后看来,这是一个快速而肮脏的答案,可能并不适用于所有情况。要获得可靠的解决方案,请参阅Tim Down's answer(在此处复制粘贴,因为此答案仍在获得观看和支持):

  

使用keyup事件无法可靠地执行此操作。如果你想知道   关于键入的字符的一些东西,你必须使用   而是按键事件。

     

以下示例将在大多数浏览器中始终有效   你应该注意一些边缘情况。对于什么是   我认为关于此的权威指南,请参阅   http://unixpapa.com/js/key.html

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

keyupkeydown为您提供有关物理密钥的信息   被压了。在标准布局中的标准美国/英国键盘上   看起来keyCode属性之间存在相关性   这些事件及其代表的角色。但事实并非如此   可靠:不同的键盘布局会有不同的映射。


以下是原始答案,但不正确,可能无法在所有情况下可靠地运作。

要将键码与单词字符匹配(例如,a将匹配。space不会)

$("input").keyup(function(event)
{ 
    var c= String.fromCharCode(event.keyCode);
    var isWordcharacter = c.match(/\w/);
}); 

好的,这是一个快速的答案。方法是相同的,但要注意键码问题,请参阅quirksmode中的article

答案 2 :(得分:11)

这对我有帮助:

$("#input").keyup(function(event) {
        //use keyup instead keypress because:
        //- keypress will not work on backspace and delete
        //- keypress is called before the character is added to the textfield (at least in google chrome) 
        var searchText = $.trim($("#input").val());

        var c= String.fromCharCode(event.keyCode);
        var isWordCharacter = c.match(/\w/);
        var isBackspaceOrDelete = (event.keyCode == 8 || event.keyCode == 46);

        // trigger only on word characters, backspace or delete and an entry size of at least 3 characters
        if((isWordCharacter || isBackspaceOrDelete) && searchText.length > 2)
        { ...

答案 3 :(得分:10)

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
    }
});

答案 4 :(得分:4)

如果您只需要排除enterescapespacebar个键,则可以执行以下操作:

$("#text1").keyup(function(event) {
if (event.keyCode != '13' && event.keyCode != '27' && event.keyCode != '32') {
     alert('test');
   }
});

See it actions here.

您可以参考complete list of keycode here进行进一步修改。

答案 5 :(得分:4)

我想做到这一点,我想到了一个解决方案,包括 keyup keypress 事件。

(我还没有在所有浏览器中对其进行测试,但我使用了在http://unixpapa.com/js/key.html编译的信息)

编辑:将其重写为jQuery插件。

(function($) {
    $.fn.normalkeypress = function(onNormal, onSpecial) {
        this.bind('keydown keypress keyup', (function() {
            var keyDown = {}, // keep track of which buttons have been pressed
                lastKeyDown;
            return function(event) {
                if (event.type == 'keydown') {
                    keyDown[lastKeyDown = event.keyCode] = false;
                    return;
                }
                if (event.type == 'keypress') {
                    keyDown[lastKeyDown] = event; // this keydown also triggered a keypress
                    return;
                }

                // 'keyup' event
                var keyPress = keyDown[event.keyCode];
                if ( keyPress &&
                     ( ( ( keyPress.which >= 32 // not a control character
                           //|| keyPress.which == 8  || // \b
                           //|| keyPress.which == 9  || // \t
                           //|| keyPress.which == 10 || // \n
                           //|| keyPress.which == 13    // \r
                           ) &&
                         !( keyPress.which >= 63232 && keyPress.which <= 63247 ) && // not special character in WebKit < 525
                         !( keyPress.which == 63273 )                            && //
                         !( keyPress.which >= 63275 && keyPress.which <= 63277 ) && //
                         !( keyPress.which === event.keyCode && // not End / Home / Insert / Delete (i.e. in Opera < 10.50)
                            ( keyPress.which == 35  || // End
                              keyPress.which == 36  || // Home
                              keyPress.which == 45  || // Insert
                              keyPress.which == 46  || // Delete
                              keyPress.which == 144    // Num Lock
                              )
                            )
                         ) ||
                       keyPress.which === undefined // normal character in IE < 9.0
                       ) &&
                     keyPress.charCode !== 0 // not special character in Konqueror 4.3
                     ) {

                    // Normal character
                    if (onNormal) onNormal.call(this, keyPress, event);
                } else {
                    // Special character
                    if (onSpecial) onSpecial.call(this, event);
                }
                delete keyDown[event.keyCode];
            };
        })());
    };
})(jQuery);

答案 6 :(得分:0)

我从不喜欢验证键代码。我的方法是查看输入内容是否包含文本(任何字符),确认用户正在输入文本而没有其他字符

$('#input').on('keyup', function() {
    var words = $(this).val();
    // if input is empty, remove the word count data and return
    if(!words.length) {
        $(this).removeData('wcount');
        return true;
    }
    // if word count data equals the count of the input, return
    if(typeof $(this).data('wcount') !== "undefined" && ($(this).data('wcount') == words.length)){
        return true;
    }
    // update or initialize the word count data
    $(this).data('wcount', words.length);
    console.log('user tiped ' + words);
    // do you stuff...
});
<html lang="en">
  <head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  </head>
  <body>
  <input type="text" name="input" id="input">
  </body>
</html>