jQuery keypress enter未起作用

3

我尝试使用keypress从中获取文本,以更新


虽然我不确定这是否是原因,但尝试使用.on可能是个好主意:http://api.jquery.com/on/。此外,您可以使用`$(this)`获取触发事件的当前对象。 - Sayan Pal
3个回答

6
使用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”的控制台消息。


谢谢!那个有效了!你有什么想法为什么我的回车键没有记录(“hello”)? - Kaisin Li
回车键可以工作,但它正在提交表单...这就是为什么你没有看到它的原因。我已经更新了我的代码,上面放置了alert,你可以看到enter键正常工作。 - Muthu Kumaran
是的,keyup有效,keypress无效。 - shareef

0

keypress 函数在按下键时立即触发。您应该使用 keyup,因为它会在松开键时触发。


谢谢!当Muthu提出建议时,我尝试了那个方法。你有什么想法为什么我的回车键没有记录(“hello”)? - Kaisin Li

0

你需要使用 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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接