如何在jQuery中实现回车键触发处理功能?按下回车即执行操作
How to Trigger Search Action with Enter Key in jQuery
Hey there! Let's get your search functionality working with both the button click and the Enter key press. Here's how to modify your existing code to make that happen, with clean, reusable logic:
Step 1: Refactor Your Logic into a Reusable Function
First, let's pull the toggle animation logic out into its own function. This way we can call it from both the button click and the Enter key event, avoiding duplicate code.
Full Modified Code
HTML (no changes needed here, unless you want to double-check):
<form id="top-search-form" class="header-search-light"> <input type="text" class="search-input" placeholder="Search...."> <button type="button" class="search-button">Search</button> </form>
jQuery Code:
// Reusable function to handle the search toggle animation function handleSearchToggle() { const target = $(this).closest('#top-search-form').find('input.search-input'); target.animate({ width: ["toggle", "swing"], height: ["toggle", "swing"], opacity: "toggle" }, 500, "linear"); return false; } // Existing click event handler $(document).on('click', '#top-search-form .search-button', function(e) { e.preventDefault(); handleSearchToggle.call(this); // Call our reusable function }); // New Enter key event handler for the search input $(document).on('keypress', '#top-search-form .search-input', function(e) { // Check if the pressed key is Enter (key code 13) if (e.which === 13) { e.preventDefault(); // Prevent default form submission (page refresh) handleSearchToggle.call(this); // Trigger the same toggle animation } });
Key Changes Explained:
- Reusable Function:
handleSearchToggle()holds all the animation logic, so we don't repeat code across events. Using.call(this)ensures the function uses the correct context (the element that triggered the event). - Enter Key Listener: We added a
keypressevent to the search input. When Enter is pressed (e.which === 13), we stop the default form submission (which would refresh the page) and run the same toggle action as the button click. - Robust Target Selection: Switched from
.prev()to.closest()+.find()—this is more reliable if your HTML structure ever changes (e.g., adding elements between the button and input).
Alternative (Simpler) Approach
If you don't want to refactor into a function, you can directly trigger the button's click event when Enter is pressed:
$(document).on('keypress', '#top-search-form .search-input', function(e) { if (e.which === 13) { e.preventDefault(); $('#top-search-form .search-button').click(); // Trigger button's click action } });
This works great for simple cases, but refactoring into a function is better for maintainability if you ever need to update the animation logic later.
内容的提问来源于stack exchange,提问作者adjie dwi sandy
相关产品推荐
相关产品推荐

