简体   繁体   中英

Simple way to compare a key pressed to a character in jQuery?

You can get the keyCode of a key pressed in jQuery:

$('#myField').keydown(function(event) {
    console.log(event.which);
});

How do I compare that to a letter? I could, of course, find out the keyCode of that letter, but I don't know ahead of time what that letter is. So I could convert every letter to a keyCode and look that up in an object. I have to imagine there's an easier way for this common situation?

Does myLetter.charCodeAt(0) always give me the same number as event.which for the same letter?

您需要使用String.fromCharCode将Unicode数字转换为字符:

 String.fromCharCode(event.keyCode)

I guess you want to use this:

String.fromCharCode();

use it here:

$('#myField').keydown(function(e) {
    var kc = e.which || e.keyCode;
    console.log(String.fromCharCode(kc).toUpperCase() == "A"); // should log true if
    // "A" character is pressed.
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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