2012-10-02 119 views
4

我找不到如何獲得按鍵的值。 我現在有獲取按鍵的鍵值

$('#info_price').bind('keydown',function(evt){ 
    alert(evt.keyCode); 

,但它返回「49」當我按下,而不是返回「1」 1。

編輯:我知道密鑰'1'的Ascii代碼。

最終目標是讓人們只將數字寫入輸入。所以我想檢測非數字並不顯示它們。

+5

49是鍵 '1' – Andreas

+1

@Andreas這只是重合的[ASCII碼(http://www.asciitable.com/)。 – Neil

回答

11

由於它在半月談記者說這是ASCII代碼。爲了得到它你可以做的字符:

alert(String.fromCharCode(evt.keyCode)); 
+3

請注意,鍵碼與字符碼不同。對於簡單的鍵,它們的代碼對應於它們的字符對應物,但是對於例如字母鍵以大寫字母結尾。你需要[keypress'事件](http://jsfiddle.net/3wThj/)來獲取字符代碼。 – pimvdb

+0

因此,對於一個azerty鍵盤,我需要按Shift + 1來顯示一個。當我先按住Shift時,這個解決方案也不能正常工作。 – bl0b

+0

@ bl0b:'keypress'可能有效,請參閱我上面評論中的鏈接。 – pimvdb

2

這裏是一個完全完成代碼爲你一起工作(不是我的,但我用它):

http://www.selfcontained.us/2009/09/16/getting-keycode-values-in-javascript/

keycode = { 

    getKeyCode : function(e) { 
     var keycode = null; 
     if(window.event) { 
      keycode = window.event.keyCode; 
     }else if(e) { 
      keycode = e.which; 
     } 
     return keycode; 
    }, 

    getKeyCodeValue : function(keyCode, shiftKey) { 
     shiftKey = shiftKey || false; 
     var value = null; 
     if(shiftKey === true) { 
      value = this.modifiedByShift[keyCode]; 
     }else { 
      value = this.keyCodeMap[keyCode]; 
     } 
     return value; 
    }, 

    getValueByEvent : function(e) { 
     return this.getKeyCodeValue(this.getKeyCode(e), e.shiftKey); 
    }, 

    keyCodeMap : { 
     8:"backspace", 9:"tab", 13:"return", 16:"shift", 17:"ctrl", 18:"alt", 19:"pausebreak", 20:"capslock", 27:"escape", 32:" ", 33:"pageup", 
     34:"pagedown", 35:"end", 36:"home", 37:"left", 38:"up", 39:"right", 40:"down", 43:"+", 44:"printscreen", 45:"insert", 46:"delete", 
     48:"0", 49:"1", 50:"2", 51:"3", 52:"4", 53:"5", 54:"6", 55:"7", 56:"8", 57:"9", 59:";", 
     61:"=", 65:"a", 66:"b", 67:"c", 68:"d", 69:"e", 70:"f", 71:"g", 72:"h", 73:"i", 74:"j", 75:"k", 76:"l", 
     77:"m", 78:"n", 79:"o", 80:"p", 81:"q", 82:"r", 83:"s", 84:"t", 85:"u", 86:"v", 87:"w", 88:"x", 89:"y", 90:"z", 
     96:"0", 97:"1", 98:"2", 99:"3", 100:"4", 101:"5", 102:"6", 103:"7", 104:"8", 105:"9", 
     106: "*", 107:"+", 109:"-", 110:".", 111: "/", 
     112:"f1", 113:"f2", 114:"f3", 115:"f4", 116:"f5", 117:"f6", 118:"f7", 119:"f8", 120:"f9", 121:"f10", 122:"f11", 123:"f12", 
     144:"numlock", 145:"scrolllock", 186:";", 187:"=", 188:",", 189:"-", 190:".", 191:"/", 192:"`", 219:"[", 220:"\\", 221:"]", 222:"'" 
    }, 

    modifiedByShift : { 
     192:"~", 48:")", 49:"!", 50:"@", 51:"#", 52:"$", 53:"%", 54:"^", 55:"&", 56:"*", 57:"(", 109:"_", 61:"+", 
     219:"{", 221:"}", 220:"|", 59:":", 222:"\"", 188:"<", 189:">", 191:"?", 
     96:"insert", 97:"end", 98:"down", 99:"pagedown", 100:"left", 102:"right", 103:"home", 104:"up", 105:"pageup" 
    } 

}; 
0

關鍵代碼不直接映射到字符值。相反,您需要查看keypress事件,該事件爲您提供charCode屬性。然後你可以使用String.fromCharCode將它變成一個字符串。

0

爲了得到ASCII的性格:

String.fromCharCode(); 

ASCII成字符串。

5

對於那些誰,現在谷歌,像我

$('input').on('keydown', function(e) { 
    console.log(e.key); 
});​ 
+0

太簡單了 - 最好的一個呢。 – BradM