如何知道.keyup()是一个字符键(jQuery) [英] How to know if .keyup() is a character key (jQuery)

查看:140
本文介绍了如何知道.keyup()是一个字符键(jQuery)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 */
}

});


推荐答案

注意这是一个快速而肮脏的答案,可能无法在所有情况下工作。要有一个可靠的解决方案,请参阅 Tim Down的答案(复制粘贴在这里,因为这个答案仍然得到意见和upvote):

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


你不能使用keyup事件可靠地执行此操作。如果你想知道
关于键入的字符,你必须使用
keypress事件。

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.

以下示例将工作大多数浏览器中的所有时间,但
有一些你应该注意的边缘情况。对于
中的什么,我的看法是关于此的最终指南,请参阅
http:/ /unixpapa.com/js/key.html

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 keydown 为您提供按钮
的物理键的信息。在标准布局的标准美国/英国键盘上,
看起来像这些事件的
的$ code> keyCode 属性之间存在相关性,代表。但是,这不是
可靠:不同的键盘布局将有不同的映射。

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.






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

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

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

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

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

这篇关于如何知道.keyup()是一个字符键(jQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆