原生JavaScript搜索功能优化:如何实现点击按钮后才展示搜索结果?
Got it, let's tweak your code so the search results only show up when the user clicks the "Search" button (or hits Enter, which is a nice usability bonus). Here's what you need to change:
Step 1: Update the HTML
First, give your button an id so we can easily target it in JavaScript:
<input autocomplete="off" type="search" id="search" placeholder="Search"> <button type="submit" id="searchBtn">Search</button> <ul id="results"></ul>
Step 2: Modify the JavaScript Code
We'll swap out the real-time input listener for a button click listener, and add support for the Enter key too. Here's the updated code with comments explaining the changes:
document.addEventListener('DOMContentLoaded', function(event) { const search = document.getElementById('search'); const results = document.getElementById('results'); const searchBtn = document.getElementById('searchBtn'); // Grab the button element let data = []; let search_term = ''; // Fetch JSON data like before fetch('/search.json') .then(response => response.json()) .then(data_server => { data = data_server; }); // Wrap search logic in a reusable function const runSearch = () => { search_term = search.value.toLowerCase(); showList(); }; // Trigger search on button click searchBtn.addEventListener('click', runSearch); // Optional: Let users press Enter to search (common expected behavior) search.addEventListener('keydown', event => { if (event.key === 'Enter') { runSearch(); } }); // Your original result display function stays the same const showList = () => { results.innerHTML = ''; if (search_term.length <= 0) return; const match = new RegExp(`${search_term}`, 'gi'); let result = data.filter(name => match.test(name.title) || match.test(name.meta_description) || match.test(name.tags)); if (result.length == 0) { const li = document.createElement('li'); li.innerHTML = `No results found`; results.appendChild(li); } result.forEach(e => { const li = document.createElement('li'); li.innerHTML = `<a href="${e.url}">${e.title}</a><br>${e.meta_description}`; results.appendChild(li); }); }; });
Key Changes Explained:
- Added a
runSearchfunction to bundle the logic of grabbing the search term and displaying results – this keeps code clean since we use it for both button clicks and Enter presses. - Replaced the
inputevent listener (which ran on every keystroke) with aclicklistener on the search button. - Added an optional
keydownhandler to support Enter key submission, which makes the search feel more intuitive for users. - Kept your original
showListfunction intact because it already handles filtering and displaying results correctly.
Now results will only appear when the user explicitly triggers the search, either by clicking the button or hitting Enter in the input field.
内容的提问来源于stack exchange,提问作者rocco
相关产品推荐
相关产品推荐

