如何使用 jQuery .keyup() 函数捕捉键盘输入
How to catch keyboard input with jQuery .keyup() function
我正在开发一个简单的刽子手游戏,我试图用 keyup()
捕捉用户输入,但是当我将它登录到控制台时,我意识到有些地方不正常.. .这是我的代码:
$(document).keyup(function(e) {
userInput = e.value;
console.log(userInput);
});
我也试过这样做,但也没用。
$(document).keyup(function(e) {
userInput = $(this).val();
console.log(userInput);
});
哦,对了,userInput是一个全局变量。
$( "#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>
Description: For key or mouse events, this property indicates the specific key or button that was pressed.
您必须从活动的 target
属性 中获取 value
。尝试以下方式:
$('#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"/>
我正在开发一个简单的刽子手游戏,我试图用 keyup()
捕捉用户输入,但是当我将它登录到控制台时,我意识到有些地方不正常.. .这是我的代码:
$(document).keyup(function(e) {
userInput = e.value;
console.log(userInput);
});
我也试过这样做,但也没用。
$(document).keyup(function(e) {
userInput = $(this).val();
console.log(userInput);
});
哦,对了,userInput是一个全局变量。
$( "#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>
Description: For key or mouse events, this property indicates the specific key or button that was pressed.
您必须从活动的 target
属性 中获取 value
。尝试以下方式:
$('#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"/>