如何使用jQuery .keyup()函数捕获键盘输入

时间:2017-03-15 04:58:29

标签: javascript jquery user-input keyup

在一个简单的刽子手游戏上工作,我试图用keyup()抓住用户输入,但是当我将它记录到控制台时我意识到某些事情并非如此工作正常......这是我的代码:

$(document).keyup(function(e) {

    userInput = e.value;
    console.log(userInput);

});

我也试过这样做,但它也没有用。

$(document).keyup(function(e) {

    userInput = $(this).val();
    console.log(userInput);

});

哦,顺便说一下, userInput是一个全局变量。

2 个答案:

答案 0 :(得分:3)

您必须从活动的#encrypt user_input = input ("Enter string: ") for char in user_input: #for every character in input cipher_num = (ord(char))+3%26 #using ordinal to find the number cipher= '' cipher = chr(cipher_num) # using chr to convert back to a letter cipher_text = '' #add all values to string cipher_text = (cipher_text+cipher) print (cipher_text) #decrypt for char in cipher_text: #for every character in the encrpted text decrypt_num = (ord(char))-3%26 decrypt= '' decrypt = chr(decrypt_num) decrypt_text = '' decrypt_text = (decrypt_text+decrypt) print(decrypt_text) 属性中获取value。请尝试以下方式:



target

$('#txtInput').on('keyup', function(e) {

    var userInput = e.target.value;
    console.log(userInput);

});




答案 1 :(得分:2)

$( "#whichkey" ).on( "keydown", function( event ) {
  $( "#log" ).html( event.type + ": " +  event.which );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="whichkey" placeholder="type something">
<div id="log"></div>

使用event.which

  

描述:对于键或鼠标事件,此属性指示已按下的特定键或按钮。