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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3977642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:59:18  来源:igfitidea点击:

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

javascriptjqueryeventskeyboardkeycode

提问by faressoft

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

如何知道 .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 */
}

});

采纳答案by Nivas

Note:In hindsight this was a quick and dirty answer, and may not work in all situations. To have a reliable solution, see Tim Down's answer(copy pasting that here as this answer is still getting views and upvotes):

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

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("Character was typed. It was: " + String.fromCharCode(e.which));
    }
});

keyupand keydowngive 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 keyCodeproperty of these events and the character they represent. However, this is not reliable: different keyboard layouts will have different mappings.

你不能用 keyup 事件可靠地做到这一点。如果您想了解有关键入的字符的信息,则必须改用 keypress 事件。

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

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

keyupkeydown为您提供有关按下的物理键的信息。在标准布局的标准美国/英国键盘上keyCode,这些事件的属性与其代表的字符之间似乎存在相关性。然而,这并不可靠:不同的键盘布局会有不同的映射。



The following was the original answer, but is not correct and may not work reliably in all situations.

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

To match the keycode with a word character (eg., awould match. spacewould not)

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

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

Ok, that was a quick answer. The approach is the same, but beware of keycode issues, see this articlein quirksmode.

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

回答by Tim Down

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

你不能用keyup事件可靠地做到这一点。如果您想了解有关键入的字符的信息,则必须改用keypress事件。

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.

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

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

keyupand keydowngive 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 keyCodeproperty of these events and the character they represent. However, this is not reliable: different keyboard layouts will have different mappings.

keyupkeydown为您提供有关按下的物理键的信息。在标准布局的标准美国/英国键盘上keyCode,这些事件的属性与其代表的字符之间似乎存在相关性。然而,这并不可靠:不同的键盘布局会有不同的映射。

回答by HankScorpio

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

我对给出的其他答案并不完全满意。他们都有某种缺陷。

Using keyPresswith event.whichis 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.keyCodewith String.fromCharCode()(keyCode and charCode are not the same!).

使用keyPresswithevent.which是不可靠的,因为您无法捕获退格或删除(如 Tarl 所述)。使用keyDown(如在 Niva 和 Tarl 的答案中)要好一些,但该解决方案有缺陷,因为它尝试使用event.keyCodewith String.fromCharCode()(keyCode 和 charCode 不一样!)。

However, what we DO have with the keydownor keyupevent is the actual key that was pressed (event.key). As far as I can tell, any keywith 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!

但是,我们对keydownorkeyup事件所做的是实际按下的键 ( event.key)。据我所知,key无论您使用哪种语言键盘,任何长度为 1 的都是一个字符(数字或字母)。如果这不是真的,请纠正我!

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

然后是来自asdf的很长的答案。这可能工作得很好,但似乎有点矫枉过正。



So here's a simple solution that will catch all characters, backspace, and delete. (Note: either keyupor keydownwill work here, but keypresswill not)

所以这里有一个简单的解决方案,可以捕获所有字符、退格和删除。(注意:要么keyupkeydown将在这里工作,但keypress不会)

$("input").keydown(function(event) {

    var isWordCharacter = event.key.length === 1;
    var isBackspaceOrDelete = event.keyCode === 8 || event.keyCode === 46;

    if (isWordCharacter || isBackspaceOrDelete) {
        // do something
    }
});

回答by TARL

This helped for me:

这对我有帮助:

$("#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)
        { ...

回答by bla

If you only need to exclude out enter, escapeand spacebarkeys, you can do the following:

如果你只需要排除出去enterescapespacebar键,可以进行以下操作:

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

See it actions here.

在这里查看它的操作。

You can refer to the complete list of keycode herefor your further modification.

您可以在此处参考完整的键码列表以进行进一步修改。

回答by asdf

I wanted to do exactly this, and I thought of a solution involving boththe keyupand the keypressevents.

我想要做的正是这一点,我想涉及解决方案的两个KEYUP按键事件。

(I haven't tested it in all browsers, but I used the information compiled at http://unixpapa.com/js/key.html)

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

Edit: rewrote it as a jQuery plugin.

编辑:将其重写为 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);

回答by lordlouis

I never liked the key code validation. My approach was to see if the input have text (any character), confirming that the user is entering text and no other characters

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

$('#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>