I have made following code, but whatever I type it will always print some odd char.
$(document).keypress(function(event) {
var character = String.fromCharCode(event.keyCode);
开发者_Go百科 $("body").append(character);
event.preventDefault();
return false;
});
keyCode
is not the same as a charCode
, they are different maps (And differ somewhat between browsers with arrow keys and such).
Think about it this way, what letter is Escape, or Delete?
You can't use String.fromCharCode()
for this purpose. You can write your own function that could recognize the characters.
change keyCode
to charCode
and Your code works. But this might not be a good idea - it's not cross browser I think. And it returns non-ascii chars as well (when you click tab key etc.) so you'd have to filter them out.
If You wanted a practical application try using an input field and get its text on keypress or something like that
精彩评论