在JavaScript中,筛选表格数据通常涉及到对表格中的行进行遍历,并根据特定条件来决定是否显示这些行。以下是一个基本的示例,展示了如何使用JavaScript来筛选表格数据:
假设我们有一个简单的HTML表格和一个输入框用于输入筛选关键词:
<input type="text" id="searchInput" onkeyup="filterTable()" placeholder="搜索...">
<table id="dataTable">
<tr>
<th>姓名</th>
<th>年龄</th>
<th>城市</th>
</tr>
<tr>
<td>张三</td>
<td>28</td>
<td>北京</td>
</tr>
<tr>
<td>李四</td>
<td>34</td>
<td>上海</td>
</tr>
<!-- 更多行... -->
</table>
以下是JavaScript代码,用于实现筛选功能:
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 = 1; 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"; // 隐藏不匹配的行
}
}
}
}
通过这种方式,你可以有效地使用JavaScript来筛选HTML表格中的数据,提升应用程序的交互性和实用性。
领取专属 10元无门槛券
手把手带您无忧上云