如何修改JavaScript代码统计表格过滤后行数并显示结果
实现表格过滤行数统计
第一步:添加统计显示区域
先在你的表格上方加一个用来展示统计结果的容器:
<div id="countDisplay"></div> <table id="myTable"> <!-- 你的表格内容 --> </table>
第二步:修改JavaScript代码
调整原有代码,加入统计逻辑:
// 获取表格行和统计容器 const trs = document.getElementById("myTable").getElementsByTagName("tr"); const countDisplay = document.getElementById("countDisplay"); // 保留你原来的事件监听 document.getElementById("search").addEventListener("input", filterRows); document.getElementById("search").addEventListener("change", filterRows); document.getElementById("search").addEventListener("click", filterRows); function filterRows(e) { const query = e.target.value.toLowerCase(); // 计算总行数:如果表格第一行是表头,就用trs.length - 1;无表头则直接用trs.length const totalRows = trs.length - 1; let matchedRows = 0; for (const tr of trs) { // 跳过表头行(如果有表头的话,让表头始终显示) if (tr === trs[0]) { tr.style.display = ""; continue; } // 判断当前行是否匹配关键词 const isMatch = tr.innerText.toLowerCase().includes(query); tr.style.display = isMatch ? "" : "none"; // 统计匹配的行数 if (isMatch) matchedRows++; } // 更新统计文字 countDisplay.textContent = `找到${matchedRows}行,共${totalRows}行`; }
适配说明
- 如果你的表格没有表头,把
const totalRows = trs.length - 1改成const totalRows = trs.length,同时删掉跳过表头的那段if (tr === trs[0])代码。 - 你原来的三种输入方式(输入、粘贴、导入选项)触发的事件,都会自动执行统计逻辑,无需额外添加监听。
内容的提问来源于stack exchange,提问作者M.Rono
相关产品推荐
相关产品推荐

