要在JavaScript中实现表格搜索功能,你可以使用以下步骤:
以下是一个简单的实现示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Table Search</title>
<style>
.hidden { display: none; }
</style>
</head>
<body>
<input type="text" id="searchInput" onkeyup="searchTable()" placeholder="Search for names..">
<table id="dataTable">
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
</tr>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
</tr>
<!-- More rows here -->
</table>
<script>
function searchTable() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("searchInput");
filter = input.value.toUpperCase();
table = document.getElementById("dataTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0]; // Check the first column
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].classList.remove("hidden");
} else {
tr[i].classList.add("hidden");
}
}
}
}
</script>
</body>
</html>
.toUpperCase()
调用。for
循环中添加更多的td
检查。for (i = 0; i < tr.length; i++) {
var found = false;
td = tr[i].getElementsByTagName("td");
for (var j = 0; j < td.length; j++) {
txtValue = td[j].textContent || td[j].innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
found = true;
break;
}
}
if (found) {
tr[i].classList.remove("hidden");
} else {
tr[i].classList.add("hidden");
}
}
通过这种方式,你可以实现一个基本的表格搜索功能,并根据需要进行扩展和优化。
领取专属 10元无门槛券
手把手带您无忧上云