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

发布于 2024-09-28 14:30:59 字数 233 浏览 5 评论 0原文

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

});

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 not enter key or shift or Esc or space ...etc
/* Do stuff */
}

});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

£烟消云散 2024-10-05 14:31:00

我正是想做到这一点,并且想到了一个同时涉及 keyupkeypress 事件的解决方案。

(我没有在所有浏览器中测试它,但我使用了 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);

I wanted to do exactly this, and I thought of a solution involving both the keyup and the keypress events.

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

Edit: rewrote it as a jQuery plugin.

(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);
呢古 2024-10-05 14:31:00

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

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

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>

喜爱纠缠 2024-10-05 14:30:59

您无法使用 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 属性和它们代表的字符之间似乎存在相关性。然而,这是不可靠的:不同的键盘布局将具有不同的映射。

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.

一念一轮回 2024-10-05 14:30:59

注意:事后看来,这是一个快速而肮脏的答案,并且可能不适用于所有情况。要获得可靠的解决方案,请参阅 蒂姆·唐的回答(将其复制粘贴到此处,因为该答案仍在获得浏览和点赞):

您无法通过 keyup 事件可靠地完成此操作。如果你想知道
有关键入的字符的信息,您必须使用
而是按键事件。

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

$("输入").keypress(function(e) {
    if (e.which !== 0) {
        Alert("已输入字符。它是:" + String.fromCharCode(e.which));
    }
});

keyupkeydown 为您提供有关物理按键的信息
被压了。在标准布局的美国/英国键盘上,
看起来 keyCode 属性之间存在相关性
这些事件及其所代表的人物。然而,这并不是
可靠:不同的键盘布局将有不同的映射。


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

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

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

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

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):

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

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.


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., a would match. space would not)

$("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 article in quirksmode.

成熟稳重的好男人 2024-10-05 14:30:59

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

keyPressevent.which 一起使用是不可靠的,因为您无法捕获退格键或删除键(如 Tarl 提到的)。
使用 keyDown (如 Niva 和 Tarl 的答案)要好一些,但该解决方案是有缺陷的,因为它尝试将 event.keyCodeString.fromCharCode( ) (keyCode 和 charCode 不一样!)。

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

然后是 asdf 的很长的答案。这可能很有效,但似乎有点矫枉过正。


因此,这里有一个简单的解决方案,可以捕获所有字符、退格键和删除。 (注意: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
    }
});

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
    }
});
高速公鹿 2024-10-05 14:30:59

这对我有帮助:

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

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)
        { ...
总以为 2024-10-05 14:30:59

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

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

在此处查看操作。

您可以参考 这里有完整的键码列表供您进一步修改。

If you only need to exclude out enter, escape and spacebar keys, you can do the following:

$("#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 here for your further modification.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文