English 中文(简体)
Javascript: 事件。 和 CharCodeAt 一起合作
原标题:Javascript: event.which and charCodeAt working together

我从CharCode中选择用户输入的事件。 在按键上输入的事件, 并使用 String. 输出 。

User types: a
event.which: 67
Outputs: A

对于数字和字母,我可以处理, 但是在谈论特殊人物时, 我得到了完全不同的产出。

User types: -
event.which: 189
Outputs: ½

经过一项研究,我发现了功能“强度”CodeAt

不幸的是,我不能使用charCodeAt,因为直接来自$(文件)而不是字段的用户类型。

那么,问题是,我能否从关键新闻活动 找到正确的炭码? 什么?

如果仍然无法解答我的疑问,我给你做了一个Fiddle =

最佳回答

使用 keeypress 事件, 而不是 keysup 。 它报告字符代码, 而不是关键代码, 当输入实际字符时, 它会触发, 而不是当打开密钥时, 所以它也会处理重复字符 。

$( #field ).focus().keypress(function(e){
  var key = e.which;
  $("#key").val(String.fromCharCode(key));
});

http://jsfiddle.net/Guffa/QCHt7/1/

Edit:

如果您想在所有地方抓住按键, 您就必须在文档中, 以及任何消耗按键的元素上挂勾事件。 例如, 文本框将处理按键, 并且不会让按键泡到父元素上 。

问题回答

您正在使用密钥, 一个报告按下密钥的事件, 而不是输入哪个字符 。 您应该使用按键来代替按键, 比如 :

$(document).keyup(function(e){
    console.log(String.fromCharCode(e.which));
});

""http://api.jquery.com/keypress/"rel="no follow">jquery doc on keypress :

Note that keydown and keyup provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress. An uppercase "A" is reported as 65 by all events. Because of this distinction, when catching special keystrokes such as arrow keys, .keydown() or .keyup() is a better choice.





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签