如何用JavaScript统计HTML表格中.CountTwo类的可见行数
解决HTML表格中统计可见.CountTwo行的问题
问题分析
你当前的count.push(document.querySelectorAll('.CountTwo'))代码存在两个核心问题:
- 每次匹配到符合过滤条件的行时,都会把整个页面所有.CountTwo元素的NodeList推到count数组里,导致count的长度等于匹配到的行数,而非实际可见的.CountTwo元素数量
- 即使行被隐藏,这些元素依然会被重复统计,完全不符合“可见行”的统计要求
解决方案
我们可以在过滤行的同时直接检查当前可见行是否包含.CountTwo元素,或者在过滤完成后统一统计。下面是两种可行的优化方案:
方案一:遍历行时同步计数
修改后的JavaScript代码:
function myFunction() { if (document.getElementById('name').checked) { const input = document.getElementById("myInput"); const filter = input.value.toUpperCase(); const table = document.getElementById("MyTable"); const tr = table.getElementsByTagName("tr"); let count = 0; let rowsFound = 0; // 遍历所有表格行 for (let i = 0; i < tr.length; i++) { const td = tr[i].getElementsByTagName("td")[1]; if (td) { const txtValue = td.textContent || td.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { tr[i].style.display = ""; rowsFound++; // 检查当前可见行是否包含.CountTwo元素,有则计数+1 if (tr[i].querySelector('.CountTwo')) { count++; } } else { tr[i].style.display = "none"; } } } document.getElementById("archieve").innerHTML = count; document.getElementById("statistic").innerHTML = rowsFound; } }
修改点说明
- 将
count从数组改为数字类型,直接累加计数,避免重复统计 - 在每行设置为可见时,通过
tr[i].querySelector('.CountTwo')检查当前行是否包含目标类元素,存在则计数+1 - 使用
const/let替代var,提升代码规范性
方案二:过滤完成后统一统计
如果更倾向于简洁的写法,可以在过滤结束后用CSS选择器直接筛选可见行中的.CountTwo元素:
function myFunction() { if (document.getElementById('name').checked) { const input = document.getElementById("myInput"); const filter = input.value.toUpperCase(); const table = document.getElementById("MyTable"); const tr = table.getElementsByTagName("tr"); let rowsFound = 0; // 遍历过滤行 for (let i = 0; i < tr.length; i++) { const td = tr[i].getElementsByTagName("td")[1]; if (td) { const txtValue = td.textContent || td.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { tr[i].style.display = ""; rowsFound++; } else { tr[i].style.display = "none"; } } } // 统计可见行中的.CountTwo元素数量 const visibleCountTwoRows = document.querySelectorAll('#MyTable tr:not([style*="display: none"]) .CountTwo'); document.getElementById("archieve").innerHTML = visibleCountTwoRows.length; document.getElementById("statistic").innerHTML = rowsFound; } }
这种方式通过tr:not([style*="display: none"])精准筛选出所有可见行,再统计其中的.CountTwo元素数量,逻辑更清晰。
内容的提问来源于stack exchange,提问作者Baa My
相关产品推荐
相关产品推荐

