如何使用jQuery .keyup()函数捕获键盘输入
问题描述:
处理一个简单的刽子手游戏,我试图用 keyup()
来捕获用户输入,但是当我将它记录到控制台时我就是意识到某事不正常......这是我的代码:
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);
});
哦,顺便说一下, userInput是一个全局变量。
答
您必须从目标中获取
活动的属性。请尝试以下方式:值
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"/>