[英]jQuery keypress enter not working
我尝试使用按键来获取文本以更新 . 我的 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
函数会在keypress
某个键时立即触发。 您想使用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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.