我尝试使用keypress从中获取文本,以更新
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
键将提交表单并重定向页面。您可能无法看到“hello”的控制台消息。
alert
,你可以看到enter
键正常工作。 - Muthu Kumarankeypress
函数在按下键时立即触发。您应该使用 keyup
,因为它会在松开键时触发。
你需要使用 keyup
,因为 keypress 会在按下键时触发值,这与释放键是分开的。
有一些改变可以进行。 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>
.on
可能是个好主意:http://api.jquery.com/on/。此外,您可以使用`$(this)`获取触发事件的当前对象。 - Sayan Pal