在JavaScript中,搜索和筛选表格通常涉及对表格中的数据进行查找和过滤,以满足特定的条件。这可以通过遍历表格的行和单元格,并应用条件逻辑来实现。
以下是一个简单的示例,展示如何在JavaScript中实现基于文本的搜索功能:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Table Search and Filter</title>
<style>
.hidden { display: none; }
</style>
</head>
<body>
<input type="text" id="searchInput" onkeyup="filterTable()" placeholder="Search for names..">
<table id="dataTable">
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
<tr>
<td>John Doe</td>
<td>30</td>
<td>New York</td>
</tr>
<tr>
<td>Jane Smith</td>
<td>25</td>
<td>Los Angeles</td>
</tr>
<!-- More rows here -->
</table>
<script>
function filterTable() {
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];
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>
问题:搜索功能不响应或响应缓慢。
原因:
解决方法:
通过上述方法,可以有效提升搜索和筛选表格的性能和用户体验。
领取专属 10元无门槛券
手把手带您无忧上云