…">
当前位置:首页 > JavaScript

js实现搜索框

2026-03-16 04:13:04JavaScript

实现基础搜索框功能

创建一个基本的HTML结构,包含输入框和搜索按钮:

<input type="text" id="searchInput" placeholder="输入搜索内容">
<button id="searchButton">搜索</button>
<div id="results"></div>

添加JavaScript事件监听:

document.getElementById('searchButton').addEventListener('click', function() {
  const searchTerm = document.getElementById('searchInput').value;
  if (searchTerm.trim() !== '') {
    performSearch(searchTerm);
  }
});

添加实时搜索功能

实现输入时实时触发搜索:

document.getElementById('searchInput').addEventListener('input', function(e) {
  const searchTerm = e.target.value;
  if (searchTerm.length > 2) {  // 避免太短时频繁搜索
    performSearch(searchTerm);
  }
});

搜索逻辑实现

基础搜索函数示例:

js实现搜索框

function performSearch(term) {
  // 模拟数据或API调用
  const mockData = ['apple', 'banana', 'cherry', 'date'];
  const results = mockData.filter(item => 
    item.toLowerCase().includes(term.toLowerCase())
  );

  displayResults(results);
}

结果显示处理

创建结果显示函数:

function displayResults(results) {
  const resultsContainer = document.getElementById('results');
  resultsContainer.innerHTML = '';

  if (results.length === 0) {
    resultsContainer.innerHTML = '<p>未找到匹配结果</p>';
    return;
  }

  const ul = document.createElement('ul');
  results.forEach(item => {
    const li = document.createElement('li');
    li.textContent = item;
    ul.appendChild(li);
  });

  resultsContainer.appendChild(ul);
}

添加搜索历史功能

实现搜索历史记录:

let searchHistory = [];

function addToHistory(term) {
  if (!searchHistory.includes(term)) {
    searchHistory.push(term);
    if (searchHistory.length > 5) {
      searchHistory.shift();
    }
    updateHistoryDisplay();
  }
}

function updateHistoryDisplay() {
  const historyElement = document.getElementById('history');
  if (historyElement) {
    historyElement.innerHTML = searchHistory.map(item => 
      `<span class="history-item">${item}</span>`
    ).join(' ');
  }
}

完善用户体验

添加键盘事件支持:

js实现搜索框

document.getElementById('searchInput').addEventListener('keypress', function(e) {
  if (e.key === 'Enter') {
    const searchTerm = document.getElementById('searchInput').value;
    if (searchTerm.trim() !== '') {
      performSearch(searchTerm);
    }
  }
});

添加加载状态指示:

function setLoadingState(isLoading) {
  const button = document.getElementById('searchButton');
  button.disabled = isLoading;
  button.textContent = isLoading ? '搜索中...' : '搜索';
}

与后端API集成

实际项目中通常需要调用API:

async function performApiSearch(term) {
  try {
    setLoadingState(true);
    const response = await fetch(`/api/search?q=${encodeURIComponent(term)}`);
    const data = await response.json();
    displayResults(data.results);
    addToHistory(term);
  } catch (error) {
    console.error('搜索失败:', error);
    displayResults([]);
  } finally {
    setLoadingState(false);
  }
}

样式优化建议

添加基础CSS样式:

#searchInput {
  padding: 8px;
  width: 300px;
  margin-right: 10px;
}

#searchButton {
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  cursor: pointer;
}

#results {
  margin-top: 20px;
}

.history-item {
  cursor: pointer;
  color: blue;
  margin-right: 10px;
}

标签: js
分享给朋友:

相关文章

js实现文件下载

js实现文件下载

使用 a 标签下载文件 通过动态创建 a 标签并设置 download 属性实现文件下载。适用于已知文件 URL 或 Blob 数据的情况。 function downloadFile(url, f…

原生js实现轮播图

原生js实现轮播图

基本结构搭建 HTML部分需要包含轮播图容器、图片列表及导航按钮。结构示例如下: <div class="slider-container"> <div class="slid…

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = document…

js实现论坛

js实现论坛

实现论坛的基本功能 使用JavaScript实现一个论坛需要结合前端和后端技术。前端可以使用React、Vue或Angular等框架,后端可以选择Node.js配合Express或Koa框架。数据库可…

js实现报表

js实现报表

使用JavaScript实现报表 在JavaScript中实现报表功能可以通过多种方式完成,常见的方法包括使用原生JavaScript、第三方库(如Chart.js、D3.js)或结合后端数据渲染。以…

js手势实现

js手势实现

手势识别实现方法 在JavaScript中实现手势识别通常涉及监听触摸事件(touchstart、touchmove、touchend)或鼠标事件(mousedown、mousemove、mouseu…