如何过滤/搜索列表
学习如何使用 JavaScript 创建过滤列表。
过滤列表
如何使用 JavaScript 搜索列表中的项目。
创建搜索列表
第一步 - 添加 HTML:
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.."> <ul id="myUL"> <li><a href="#">Adele</a></li> <li><a href="#">Agnes</a></li> <li><a href="#">Billy</a></li> <li><a href="#">Bob</a></li> <li><a href="#">Calvin</a></li> <li><a href="#">Christina</a></li> <li><a href="#">Cindy</a></li> </ul>
注意:在此演示中,我们使用 href="#",因为我们没有页面可以链接到。在实际应用中,这应该是指向特定页面的真实 URL。
第二步 - 添加 CSS:
设置输入元素和列表的样式:
#myInput {
background-image: url('/css/searchicon.png'); /* 向输入框添加搜索图标 */
background-position: 10px 12px; /* 定位搜索图标 */
background-repeat: no-repeat; /* 不要重复图标图像 */
width: 100%; /* 全宽 */
font-size: 16px; /* 增加字体大小 */
padding: 12px 20px 12px 40px; /* 添加一些内边距 */
border: 1px solid #ddd; /* 添加灰色边框 */
margin-bottom: 12px; /* 在输入框下方添加一些空间 */
}
#myUL {
/* 移除默认的列表样式 */
list-style-type: none;
padding: 0;
margin: 0;
}
#myUL li a {
border: 1px solid #ddd; /* 为所有链接添加边框 */
margin-top: -1px; /* 防止双边框 */
background-color: #f6f6f6; /* 灰色背景色 */
padding: 12px; /* 添加一些内边距 */
text-decoration: none; /* 移除默认文本下划线 */
font-size: 18px; /* 增加字体大小 */
color: black; /* 添加黑色文本颜色 */
display: block; /* 使其成为块级元素以填充整个列表 */
}
#myUL li a:hover:not(.header) {
background-color: #eee; /* 为所有链接(除了标题)添加悬停效果 */
}
第三步 - 添加 JavaScript:
<script>
function myFunction() {
// Declare variables
var input, filter, ul, li, a, i, txtValue;
input = document.getElementById('myInput');
filter = input.value.toUpperCase();
ul = document.getElementById("myUL");
li = ul.getElementsByTagName('li');
// 遍历所有列表项,并隐藏那些与搜索查询不匹配的项
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
</script>
提示:如果要执行区分大小写的搜索,请删除 toUpperCase()。
相关页面
教程:如何过滤/搜索表格