jQuery按键输入无效



我尝试使用按键从中获取文本以更新中的文本。我的html看起来像这样:

<p>words words words <i>test</i> more words</p>
<div id="newWord">
<form>
<input type="text" placeholder="New Hashtag"></input>
</form>
</div>

我的jQuery看起来像这样:

$(document).ready(function () {
$("input").keypress(
function (e) {
var currentInput = $("input").val();
console.log(currentInput);
if (e.keyCode === 13) {
console.log('hello');
}
}
);
})

我的控制台日志没有在第一次按键时登录,我该怎么办?而且我的"你好"从不登录。你知道为什么会这样吗?

谢谢!

使用keyup事件捕获第一个键盘字符。

$(document).ready(function () {
$("input").keyup(
function (e) {
var currentInput = $("input").val();
console.log(currentInput);
if (e.keyCode === 13) {
console.log('hello');
alert('hello');
}
}
);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>words words words <i>test</i> more words</p>
<div id="newWord">
<form>
<input type="text" placeholder="New Hashtag">
</form>
</div>

注意:点击Enter键将提交表单,并重定向页面。您可能看不到"你好"的控制台消息

keypress函数在按键时向右触发。您想使用keyup,因为释放密钥时会触发。

您需要使用keyup,因为按键一按下就会触发值,这与释放按键是分开的。

几乎没有什么可以做的改变。input是一个自封闭标签。此外,最好在函数中使用$(this),因为它只会从触发事件的输入中获得值。

这里可能有陷阱。按下enter/return键,您可能会看到表单正在提交

$(document).ready(function() {
$("input").keyup(function(e) {
var currentInput = $(this).val();
console.log(currentInput);
if (e.keyCode == 13) {
console.log('hello');
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>words words words <i>test</i> more words</p>
<div id="newWord">
<form>
<input type="text" placeholder="New Hashtag">
</form>
</div>