如何解码从jQuery的keydown()的事件处理程序按下的字符

我需要从jQuery的keydown函数调用的处理程序中找出哪个字符被input到文本字段中。 key.which只给我键码,但我需要找出哪个ASCII字符key代表。 我该怎么做呢?

对于字符input,build议使用keypress() ,它将报告按下的字符的实际ASCII码。 它会自动处理字母大小写,并忽略非字符按压。 无论哪种情况,您都可以使用fromCharCode()将其转换为string表示forms。 例如

 var c = String.fromCharCode(e.which) // or e.keyCode 

只要记住,对于keydown()keyup() ,您将不得不使用e.shiftKey状态跟踪案例。

keyPress事件是您需要获取哪个字符的input。 ( 请参阅下面的keydown事件的解决方法 )。

keydownkeyup提供了一个代码,指示哪个键被按下,而keypress显示哪个字符被input。

使用jQuery e.which你可以得到关键的代码,并使用String.fromCharCode你可以得到被按下的特定字符(包括shiftKey )。

演示: http : //jsfiddle.net/9TyzP/3

码:

 element.on ('keypress', function (e) { console.log(String.fromCharCode(e.which)); }) 

注意我说jQuery的电子,这是因为不同的浏览器使用不同的属性来存储这些信息。 jQuery对.which属性进行规范化处理,以便您可以可靠地使用它来检索关键代码。

针对keydown解决方法

但是,您可以编写一个简单的解决方法来获取按下的字符在keydown工作。解决方法是创build一个对象作为charCode键没有Shift键,值是Shift键。

注意:正如@Sajjan Sarkar指出的那样,从不同浏览器返回的键码值有一些差异。 在这里阅读更多

更新了DEMO代码以规范化跨浏览器keyCode值。 在IE 8,FF和Chrome中进行testing和validation。

下面的完整代码和更新DEMO: http : //jsfiddle.net/S2dyB/17/

 $(function() { var _to_ascii = { '188': '44', '109': '45', '190': '46', '191': '47', '192': '96', '220': '92', '222': '39', '221': '93', '219': '91', '173': '45', '187': '61', //IE Key codes '186': '59', //IE Key codes '189': '45' //IE Key codes } var shiftUps = { "96": "~", "49": "!", "50": "@", "51": "#", "52": "$", "53": "%", "54": "^", "55": "&", "56": "*", "57": "(", "48": ")", "45": "_", "61": "+", "91": "{", "93": "}", "92": "|", "59": ":", "39": "\"", "44": "<", "46": ">", "47": "?" }; $(element).on('keydown', function(e) { var c = e.which; //normalize keyCode if (_to_ascii.hasOwnProperty(c)) { c = _to_ascii[c]; } if (!e.shiftKey && (c >= 65 && c <= 90)) { c = String.fromCharCode(c + 32); } else if (e.shiftKey && shiftUps.hasOwnProperty(c)) { //get shifted keyCode value c = shiftUps[c]; } else { c = String.fromCharCode(c); } //$(element).val(c); }).on('keypress', function(e) { //$(element).val(String.fromCharCode(e.which)); }); }); 

更多关于键盘事件 –

当用户按下按键时,按键,按键和按键事件将被触发。

keydown当用户按下某个键时触发。 当用户保持按下时,它重复。

按键当一个实际的字符被插入时触发,例如,一个文本input。 当用户保持按下时,它重复。

keyup当用户释放一个键时,在该键的默认操作完成后触发。

当第一个键被按下时,发送keydown事件。 如果该键不是修饰键,则发送keypress事件。 当用户释放密钥时,发送密钥事件。

当按下某个键时,它将开始自动重复。 这会导致一系列类似于以下事件的事件:

 keydown keypress keydown keypress <<repeating until the user releases the key>> keyup 

DEMO: http : //jsfiddle.net/9TyzP/1/

keyup,keydown vs按键

keydown和keyup事件代表被按下或释放的键,而keypress事件代表被键入的字符。

DEMO: http : //jsfiddle.net/9TyzP/

参考文献:

  1. https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent

  2. http://www.quirksmode.org/dom/events/keys.html

  3. http://unixpapa.com/js/key.html

我这样做 如果值不是数字,它将忽略按键。 似乎工作没有任何问题…

  $("input").on("keypress", function(e) { if(!jQuery.isNumeric(String.fromCharCode(e.which))) return false; }); 

Selvakumar Arumugam的回答对我来说就像一个魅力…直到我testingnumpad。 所以这里有一个小的更新:

  $(document).on('keydown', function(e) { var c = e.which; if (_to_ascii.hasOwnProperty(c)) { c = _to_ascii[c]; } if (!e.shiftKey && (c >= 65 && c <= 90)) { c = String.fromCharCode(c + 32); } else if (e.shiftKey && shiftUps.hasOwnProperty(c)) { c = shiftUps[c]; } else if (96 <= c && c <= 105) { c = String.fromCharCode(c - 48); }else { c = String.fromCharCode(c); } $kd.val(c); }) 

http://jsfiddle.net/S2dyB/78/

我创build并使用上面的JavaScript类将gr转换为en字符。 它可以用于更多的语言。 它使用JQuery来更改从用户按下的值。

 var CharMapper = function (selector) { this.getLanguageMapper = function (languageSource, languageTarget) { // Check if the map is already defined. if (typeof langugageCharMap === "undefined") { langugageCharMap = {}; } if (typeof langugageCharMap[languageSource] === "undefined") { langugageCharMap[languageSource] = {}; } // Initialize or get the language mapper. if (typeof langugageCharMap[languageSource][languageTarget] === "undefined") { switch (languageSource) { case "GR": switch (languageTarget) { case "EN": langugageCharMap[languageSource][languageTarget] = { "α": "a", "ά": "a", "β": "b", "γ": "g", "δ": "d", "ε": "e", "έ": "e", "ζ": "z", "η": "h", "ή": "h", "θ": "th", "ι": "i", "ί": "i", "ϊ": "i", "ΐ": "i", "κ": "k", "λ": "l", "μ": "m", "ν": "n", "ξ": "ks", "ο": "o", "ό": "o", "π": "p", "ρ": "r", "σ": "s", "ς": "s", "τ": "t", "υ": "y", "ύ": "y", "ϋ": "y", "ΰ": "y", "φ": "f", "χ": "x", "ψ": "ps", "ω": "o", "ώ": "o", "Α": "A", "Ά": "A", "Β": "B", "Γ": "G", "Δ": "D", "Ε": "E", "Έ": "E", "Ζ": "Z", "Η": "H", "Ή": "H", "Θ": "TH", "Ι": "I", "Ί": "I", "Ϊ": "I", "Κ": "K", "Λ": "L", "Μ": "M", "Ν": "N", "Ξ": "KS", "Ο": "O", "Ό": "O", "Π": "P", "Ρ": "R", "Σ": "S", "Τ": "T", "Υ": "Y", "Ύ": "Y", "Ϋ": "Y", "Φ": "F", "Χ": "X", "Ψ": "PS", "Ω": "O", "Ώ": "O" }; break; case "GR": default: throw "Language(" + languageTarget + ") is not supported as target for Language(" + languageSource + ")."; } break; case "EN": default: throw "Language(" + languageSource + ") is not supported as source."; } } return langugageCharMap[languageSource][languageTarget]; }; // Check the existance of the attribute. var items = $(selector).find("*[data-mapkey]"); if (items.length === 0) { return; } // For each item. for (var i = 0; i < items.length; i++) { var item = items[i]; // Get the source and target language. var languages = $(item).attr("data-mapkey"); var languageSource = languages.split("_")[0]; var languageTarget = languages.split("_")[1]; // Add the event listener. var self = this; $(item).keypress(function (event) { event.stopPropagation(); // Get the mapper to use. var mapper = self.getLanguageMapper(languageSource, languageTarget); // Get the key pressed. var keyPressed = String.fromCharCode(event.which); // Get the key to set. In case it doesn't exist in the mapper, get the key pressed. var keyToSet = mapper[keyPressed] || keyPressed; // Set the key to the dom. this.value = this.value + keyToSet; // Do not propagate. return false; }); } }; 

例,

 <input type="text" data-mapkey="GR_EN" /> <script type="text/javascript"> new CharMapper("body"); </script>