js实现搜索框
实现基础搜索框功能
创建一个基本的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);
}
});
搜索逻辑实现
基础搜索函数示例:

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(' ');
}
}
完善用户体验
添加键盘事件支持:

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;
}






