问题
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