How to catch keyboard input with jQuery .keyup() function

大兔子大兔子 提交于 2019-12-08 11:27:59

问题


Working on a simple hangman game, and I'm trying to catch the user input with the keyup(), but when I log it to the console I'm realizing something isn't working right... this is my code:

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

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

});

I also tried doing this, but it isn't working either.

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

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

});

oh, by the way, userInput is a global variable.


回答1:


You have to get the value from target property of the event. Try the following way:

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

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

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Input: <input type='text' id="txtInput"/>



回答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>

Use event.which

Description: For key or mouse events, this property indicates the specific key or button that was pressed.



来源:https://stackoverflow.com/questions/42801424/how-to-catch-keyboard-input-with-jquery-keyup-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!