JavaScript 表格数据搜索
分类 编程技术
本文为大家介绍如何实现一个表格数据搜索的功能。
HTML 代码:
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="搜索...">
<table id="myTable">
<tr class="header">
<th style="width:60%;">名称</th>
<th style="width:40%;">城市</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('https://static.runoob.com/images/mix/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 {
/* 表头及鼠标移动过 tr 时添加背景 */
background-color: #f1f1f1;
}
JavaScript 代码:
function myFunction() {
// 声明变量
var input, filter, table, tr, td, i;
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) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}