JavaScript で KeyCode から文字の値を取得してトリミングする 質問する

JavaScript で KeyCode から文字の値を取得してトリミングする 質問する

これが今私が持っているものです:

$("input").bind("keydown",function(e){
    var value = this.value + String.fromCharCode(e.keyCode);
}

e.keyCodeがASCII 文字 (、、、など) ではない場合Alt、これらの値を何らかの方法で (できればルックアップ テーブルではなくプログラムで) 取得する必要があります。backspacedelarrowstrimvalue

jQueryを使用しています。

イベントを使用する必要がありますkeydownkeyPressキャプチャする必要がある特定のキー ( Esc、、など) に対してはアクティブになりません。delbackspace

setTimeout入力の値を取得するために使用できません。setTimeout(function(){},0)遅すぎます。

ベストアンサー1

私の経験では、String.fromCharCode(e.keyCode)信頼性が低いです。String.fromCharCode引数としてUnicode文字コードを想定し、e.keyCodeJavaScriptキーコードを返します。JavascriptキーコードとUnicode文字コードはない同じです! 特に、テンキーのキーは、keycode通常の数字キーとは異なる を返します (異なるキーであるため)。一方、と の文字keycodeには、 が異なるにもかかわらず、同じ が返されます(どちらの場合も同じキーを押しました) 。upperlowercasecharcodes

たとえば、通常の数字キー 1 はkeycode49 のイベントを生成し、テンキー キー 1 (オンNumlock) はkeycode97 を生成します。 を とともに使用するとString.fromCharCode、次のようになります。

String.fromCharCode(49) returns "1"
String.fromCharCode(97) returns "a"

String.fromCharCodeは、Javascript キーコードではなく、Unicode 文字コードを想定しています。キーは、生成される文字の大文字と小文字に関係なく、65 の を持つaイベントを生成します(イベントには、キーが押された場合などの修飾子もあります)。文字のUnicode は61 ですが、文字の は 41 です(たとえば、keycodeShiftacharcodeAcharcodehttp://www.utf8-chartable.de/)。しかし、これらはhex値であり、10進数に変換すると、「A」の場合は65、「a」の場合は97になりますcharcode。[1] これは、これらの値から得られる結果と一致していますString.fromCharCode

My own requirement was limited to processing numbers and ordinary letters (accepting or rejecting depending on the position in the string) and letting control characters (F-keys, Ctrl-something) through. Thus I can check for the control characters, if it's not a control character I check against a range and only then do I need to get the actual character. Given I'm not worried about case (I change all letters to uppercase anyway) and have already limited the range of keycodes, I only have to worry about the numberpad keys. The following suffices for that:

String.fromCharCode((96 <= key && key <= 105)? key-48 : key)

More generally, a function to reliably return the character from a charcode would be great (maybe as a jQuery plugin), but I don't have time to write it just now. Sorry.

I'd also mention e.which (if you're using jQuery) which normalizes e.keyCode and e.charCode, so that you don't need to worry about what sort of key was pressed. The problem with combining it with String.fromCharCode remains.

[1] I was confused for a while -. all the docs say that String.fromCharCode expects a unicode charcode, while in practice it seemed to work for ASCII charcodes, but that was I think due to the need to convert to decimal from hex, combined with the fact that ASCII charcodes and unicode decimal charcodes overlap for ordinary latin letters.

おすすめ記事