jquery 搜索框
jQuery 搜索框实现方法
基本搜索框结构
使用HTML和jQuery创建一个简单的搜索框,可以通过输入内容过滤列表或表格数据。
<input type="text" id="searchInput" placeholder="搜索...">
<ul id="searchList">
<li>苹果</li>
<li>香蕉</li>
<li>橙子</li>
<li>葡萄</li>
</ul>
jQuery 搜索功能
通过监听输入框的keyup事件,实时过滤列表项:
$(document).ready(function(){
$("#searchInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#searchList li").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
表格数据搜索
对于表格数据的搜索,可以使用类似的方法:
$("#searchInput").keyup(function(){
var value = $(this).val().toLowerCase();
$("table tr").each(function(){
var found = false;
$(this).find("td").each(function(){
if($(this).text().toLowerCase().indexOf(value) > -1){
found = true;
return false;
}
});
$(this).toggle(found);
});
});
高级搜索功能
添加延迟搜索和自动完成功能:
var searchTimer;
$("#searchInput").keyup(function(){
clearTimeout(searchTimer);
searchTimer = setTimeout(function(){
// 执行搜索逻辑
}, 500);
});
样式优化
为搜索框添加CSS样式增强用户体验:
#searchInput {
padding: 8px;
width: 200px;
border: 1px solid #ddd;
border-radius: 4px;
margin-bottom: 10px;
}
响应式设计
确保搜索框在不同设备上表现良好:
@media (max-width: 600px) {
#searchInput {
width: 100%;
}
}






