2015-06-22 65 views
-1

這種方式可行,但它讓我感到工作太辛苦。確定按下哪個鍵

問題:你如何確定哪個鍵被按下?

;(function() { 
    var Variables = {} 
    Variables.slash = false 
    $('[name=myName]').keypress(keypress) 
    function keypress(myEvent) { 
     if (myEvent.which === 47) { 
      Variables.slash = true 
     } 
    } 
    $('[name=myName]').keyup(keyup) 
    function keyup(myEvent) { 
     if (Variables.slash) { 
      Variables.slash = false 

     } 
    } 
})() 
+0

你想知道斜槓是否被按下?或者什麼意思ob變量對象和斜槓屬性? – berkyl

+0

是的,這段代碼看起來比它需要的更復雜。我只需要知道斜槓何時被按下。 –

回答

1

它可以簡化,通過以下步驟:

1

myEvent變量將包含已按下的鍵的ASCII碼斜線的ASCII碼爲47(See here

0

previous question

「清除」 的JavaScript:

<script type="text/javascript"> 
     function myKeyPress(e){ 

      var keynum; 

      if(window.event){ // IE     
       keynum = e.keyCode; 
      } 
      else if(e.which){ // Netscape/Firefox/Opera     
       keynum = e.which; 
      } 

      alert(String.fromCharCode(keynum)); 
     } 
</script> 


<form> 
    <input type="text" onkeypress="return myKeyPress(event)" /> 
</form> 

JQuery的:

$(document).keypress(function(event){ 
    alert(String.fromCharCode(event.which)); 
})