You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

原生JavaScript搜索功能优化:如何实现点击按钮后才展示搜索结果?

Solution: Trigger Search Only on Button Click

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 runSearch function 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 input event listener (which ran on every keystroke) with a click listener on the search button.
  • Added an optional keydown handler to support Enter key submission, which makes the search feel more intuitive for users.
  • Kept your original showList function 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 10:37:40