如何在 JS 事件监听器中获取正确的按键语言和大小写?
我有以下 jQuery 事件侦听器来获取文本框中按下的键:
$("#theInput").keyup(function (e) {
var charCode = e.keyCode || e.which;
alert(charCode);
/* rest of the code */
});
我的问题是如何准确获取键入的字母的代码。例如,如果我按 a 键,它将警告“65” - 无论它是 a 还是 A。如果我将输入语言切换为外语(例如日语、中文、泰语)并按a键,它仍然返回“65”而不是不同的代码来让我知道外语字符。
有没有办法解决这个问题,以便提供正确的语言和字母大小写?
I have the following jQuery event listener to get the key pressed in a text box:
$("#theInput").keyup(function (e) {
var charCode = e.keyCode || e.which;
alert(charCode);
/* rest of the code */
});
My problem is how to accurately get the code for the letter typed. For instance, if I press the a key it will alert '65' - regardless of whether it was a or A. If I switch the input language to a foreign language (e.g. Japanese, Chinese, Thai) and press the a key, it still returns '65' rather than a different code to let me know the foreign character.
Is there a way to I fix this so it gives the correct language and case of the letter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否阅读过 jQuery doco 来了解
keyup
和keydown
事件的情况工作?他们应该返回一个键代码(而不是字符代码),而不考虑当时是否按下了shift,尽管event
对象确实有一个shiftKey
属性来告诉你shift是否按下了。keyup
可让您区分与同一字符关联的不同键,这样您就可以判断数字是否是通过数字键盘输入的。您想要的事件是keypress,它返回区分大小写的字符代码。尽管我已经说过,我不确定它如何适用于外语,并且在任何情况下,整个方法都不允许用户通过从剪贴板粘贴来输入其他文本,所以这是您需要考虑的其他事情。
(顺便说一句,jQuery 标准化了
event.which
属性,因此您不需要首先检查event.keyCode
。)Have you read the jQuery doco on how the
keyup
andkeydown
events work? They are supposed to return a key code (rather than a character code) without regard for whether shift was down at the time, though theevent
object does have ashiftKey
property to tell you whether shift was down.keyup
lets you distinguish between different keys associated with the same character, so you can tell whether a digit was entered via the numeric keypad or not.The event you want is keypress, which returns a character code that differentiates between upper and lower case. Though having said that I'm not sure how it works for foreign languages, and in any case the whole approach doesn't allow for the user entering other text by pasting from the clipboard so that's something else you need to consider.
(By the way, jQuery normalises the
event.which
property so you shouldn't need to bother checkingevent.keyCode
first.)无论语言如何,密钥都是相同的。您可以使用
.shiftKey
获得这种情况,但最可靠的方法是保存实际字符:但这过于简化,因为文本可以在末尾以外的其他位置键入。您必须找到光标位置,然后获取相应的字符。
Keys are the same regardless of the language. You could get the case with
.shiftKey
, but the most reliable way is to save the actual characters:This is overly simplified, though, as text can be typed somewhere other than the end. You'd have to find the cursor position and then get the respective char.