简体   繁体   English

Jquery 不适用于第一次单击 html 输入中的回车键

[英]Jquery does not work for the first click on the enter key in an html input

I want when a user type something in an input, after pressing enter key, the jquery do something.我希望当用户在输入中键入内容时,按下回车键后,jquery 会执行某些操作。 I am using the following code, but there is a problem on the first time pressing enter key.我正在使用以下代码,但第一次按回车键时出现问题。 Actually it does not work.实际上它不起作用。 What's the problem and how to fix it?问题是什么以及如何解决?

 $('.tag-input').on('change', (e) =>{ $(this).on("keydown", event=> { if(event.which == 13 && $('.tag-input').val().length>0) alert($('.tag-input').val()); }); });
 .tag-input{ width:80%; }
 <div > <input class="tag-input" placeholder="Type something then press 'Enter' key." /> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>

The issue is because you've nested the keydown event handler within the change event.问题是因为您已将keydown事件处理程序嵌套在change事件中。 Nesting event handlers is rarely a good thing to do.嵌套事件处理程序很少是一件好事。 Use a single keydown event handler:使用单个keydown事件处理程序:

 $('.tag-input').on('keydown', e => { const $input = $(e.target); if (e.which == 13 && $input.val().trim().length > 0) console.log($input.val()); });
 .tag-input { width: 80%; }
 <div> <input class="tag-input" placeholder="Type something then press 'Enter' key." /> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>

That being said, a better approach entirely would be to wrap your input in a form element and put the required attribute on it.也就是说,一个更好的方法完全是将您的input包装在一个form元素中并在其上放置required的属性。 That way you don't need any JS at all:这样你根本不需要任何 JS:

 .tag-input { width: 80%; }
 <div> <form action="/search"> <input class="tag-input" required placeholder="Type something then press 'Enter' key." /> <button type="submit">Search</button> </form> </div>

 $('.tag-input').bind('keyup',function() { alert(this.value); });
 .tag-input{ width:80%; }
 <div > <input class="tag-input" placeholder="Type something then press 'Enter' key." /> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM