问题描述
在keydown上我从jQuery获得以下内容:
on a keydown I get the following from jQuery:
jQuery.Event
altKey: false
attrChange: undefined
attrName: undefined
bubbles: true
button: undefined
cancelable: true
charCode: 0
clientX: undefined
clientY: undefined
ctrlKey: false
currentTarget: HTMLDivElement
data: undefined
detail: 0
eventPhase: 2
fromElement: undefined
handleObj: Object
handler: function () {
isDefaultPrevented: function returnFalse() {
jQuery16106168975948821753: true
keyCode: 51
layerX: 0
layerY: 0
metaKey: true
newValue: undefined
offsetX: undefined
offsetY: undefined
originalEvent: KeyboardEvent
pageX: 0
pageY: 0
prevValue: undefined
relatedNode: undefined
relatedTarget: undefined
screenX: undefined
screenY: undefined
shiftKey: false
srcElement: HTMLDivElement
target: HTMLDivElement
timeStamp: 1320206454048
toElement: undefined
type: "keydown"
view: DOMWindow
wheelDelta: undefined
which: 51
__proto__: Object
如何获得按下的键?我试过了:
How can I get what key was pressed? I tried:
String.fromCharCode(e.keyCode)
这适用于AZ,但是如果我按@我不会得到@我得到2?
That works for A-Z, but if I press @ I don't get @ I get 2?
想法?
推荐答案
您可以捕获三个键盘事件: keyup
, keydown
和 keypress
。前两个行为与您观察到的方式相同,后者的行为与您想要的方式相同。
There are three keyboard events you can trap: keyup
, keydown
, and keypress
. The first two behave the way you've observed, and the latter behaves the way you seem to want.
您需要了解键和字符之间的区别( s)与该密钥相关联。
You need to understand the difference between a key and the character(s) associated with that key.
如事件给出了一个与该字符对应的keyCode,因此A和a将给出不同的keyCodes,2和@也是如此。 因此可能更适合您的需求。
(顺便说一句,这不是jQuery的事情,即使使用普通JavaScript也是正常的行为,尽管jQuery试图规范化行为一个这样的规范化是jQuery确保 event.which
将一致地工作,所以你应该使用 event.which
获取代码而不是 event.keyCode
。)
(By the way, this isn't a jQuery thing as such, this is normal behaviour even with "plain" JavaScript, though jQuery attempts to normalise behaviour across different browsers. One such normalisation is that jQuery makes sure that event.which
will work consistently, so you should use event.which
to get the code rather than event.keyCode
.)
这篇关于jQuery事件Keypress:按下了哪个键? A-Z,& @的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!