如何过滤/搜索表格
学习如何使用 JavaScript 创建可过滤的表格。
过滤表格
如何使用 JavaScript 在表格中搜索特定数据。
Name | Country |
---|---|
Alfreds Futterkiste | Germany |
Berglunds snabbkop | Sweden |
Island Trading | UK |
Koniglich Essen | Germany |
Laughing Bacchus Winecellars | Canada |
Magazzini Alimentari Riuniti | Italy |
North/South | UK |
Paris specialites | France |
创建可过滤的表格
第一步 - 添加 HTML:
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.."> <table id="myTable"> <tr class="header"> <th style="width:60%;">Name</th> <th style="width:40%;">Country</th> </tr> <tr> <td>Alfreds Futterkiste</td> <td>Germany</td> </tr> <tr> <td>Berglunds snabbkop</td> <td>Sweden</td> </tr> <tr> <td>Island Trading</td> <td>UK</td> </tr> <tr> <td>Koniglich Essen</td> <td>Germany</td> </tr> </table>
第二步 - 添加 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; /* 在输入框下方添加一些空间 */ } #myTable { border-collapse: collapse; /* 合并边框 */ width: 100%; /* 全宽 */ border: 1px solid #ddd; /* 添加灰色边框 */ font-size: 18px; /* 增大字体大小 */ } #myTable th, #myTable td { text-align: left; /* 文本左对齐 */ padding: 12px; /* 添加内边距 */ } #myTable tr { /* 为所有表格行添加底部边框 */ border-bottom: 1px solid #ddd; } #myTable tr.header, #myTable tr:hover { /* 为表格头部和鼠标悬停时添加灰色背景色 */ background-color: #f1f1f1; }
第三步 - 添加 JavaScript:
<script> function myFunction() { // 声明变量 var input, filter, table, tr, td, i, txtValue; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); table = document.getElementById("myTable"); tr = table.getElementsByTagName("tr"); // 遍历所有表格行,并隐藏那些与搜索查询不匹配的行 for (i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName("td")[0]; if (td) { txtValue = td.textContent || td.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } } </script>
提示:如果您想执行区分大小写的搜索,请删除 toUpperCase()
。
提示:如果要搜索国家(索引 1)而不是“名称”(索引 0),请将 tr[i].getElementsByTagName('td')[0]
更改为 [1]。
相关页面
教程:如何过滤/搜索列表