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

查看:17
本文介绍了如何知道 .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 的回答(复制粘贴到这里,因为这个答案仍然获得观看和投票):

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 事件可靠地做到这一点.如果你想知道关于键入的字符的某些信息,您必须使用代替按键事件.

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

keyupkeydown 为您提供有关物理键的信息被按下.在标准布局的标准美国/英国键盘上,它看起来 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 会匹配.space 不会)

$("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天全站免登陆