简体   繁体   English

如何在JS事件侦听器中获取正确的语言和按键大小写?

[英]How to get the correct language and case for key press in JS event listener?

I have the following jQuery event listener to get the key pressed in a text box: 我具有以下jQuery事件侦听器,以在文本框中按下键:

$("#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". 例如,如果我按“ a”键,它将发出“ 65”警报-无论它是“ a”还是“ A”。 If I switch the input language to a foreign language (eg Japanese,Chinese,Thai) and press the 'a' key, it still returns '65' rather than a different code to let me know the foreign character. 如果我将输入语言切换为外语(例如日语,中文,泰语)并按“ a”键,它仍会返回“ 65”而不是其他代码,以使我知道外来字符。

Is there a way to I fix this so it gives the correct language and case of the letter ? 有没有办法解决这个问题,以便给出正确的语言和字母大小写?

Have you read the jQuery doco on how the keyup and keydown events work? 您是否已阅读jQuery doco的有关keyupkeydown事件如何工作的信息? They are supposed to return a key code (rather than a character code) without regard for whether shift was down at the time, though the event object does have a shiftKey property to tell you whether shift was down. 他们应该返回键码(而不是字符码),而不考虑当时的shift是否向下,尽管event对象确实具有shiftKey属性来告诉您shift是否向下。 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. keyup使您可以区分与同一字符关联的不同键,从而可以判断是否通过数字键盘输入了数字。

The event you want is keypress , which returns a character code that differentiates between upper and lower case. 您想要的事件是keypress它返回一个区分大写和小写字母的字符代码。 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 checking event.keyCode first.) (顺便说一下,jQuery event.whichevent.which属性,因此您无需费心检查event.keyCode 。)

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: 您可以使用.shiftKey ,但最可靠的方法是保存实际字符:

$('#input').keyup(function(e){
  var character = this.value.slice(-1)
  console.log(character)
})

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. 您必须找到光标位置,然后获取相应的字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM