如何统计表格筛选后显示的行数?现有脚本仅统计总行数
解决筛选后表格显示行数统计问题
我看了你的问题,原来的脚本确实会统计所有<tr>元素,不管它是不是被筛选功能隐藏了——这就是为什么你得到的是总行数而不是当前显示的行数。问题出在没有判断行的可见状态,下面给你调整后的方案:
修改后的统计脚本
核心思路是在计数时,额外判断该行是否处于可见状态(你的筛选脚本应该是通过display: none来隐藏不符合条件的行)。
function CountRows() { var rowCount = 0; var table = document.getElementById("filter_table"); var rows = table.getElementsByTagName("tr"); for (var i = 0; i < rows.length; i++) { // 只统计包含<td>的行(排除表头行),且该行是可见的 if (rows[i].getElementsByTagName("td").length > 0 && isRowVisible(rows[i])) { rowCount++; } } // 弹出统计提示 var message = "Showing: " + rowCount; alert(message); // 可选:直接更新页面上的"Showing: XXX"文本,提升体验 var showingElement = document.querySelector(".showing-count"); if (showingElement) { showingElement.textContent = rowCount; } } // 辅助函数:判断元素是否可见 function isRowVisible(el) { var computedStyle = window.getComputedStyle(el); // 检查display是否为none,visibility是否为hidden return computedStyle.display !== "none" && computedStyle.visibility !== "hidden"; }
调整HTML部分(优化页面显示)
你可以把页面上的XXX替换成一个带类名的<span>,这样点击按钮后能直接更新页面显示,不用只依赖弹窗:
<?php echo"Items in table: " . count($artists) . ". Showing: <span class='showing-count'>XXX</span>. Table is sortable. Artists names are links to simple individual pages. Date is when the entry was modified."; ?> <input id="clickMe" type="button" value="clickme" onclick="CountRows();">
为什么原来的脚本失效?
你的原脚本遍历了表格中所有的<tr>元素,但筛选脚本(multifilter.js)是通过隐藏行(设置display: none)来实现过滤的——这些隐藏的行仍然存在于DOM结构中,所以原脚本会把它们也算进去。加上可见性判断后,就能精准统计当前显示的行啦。
内容的提问来源于stack exchange,提问作者Ole Sørensen
相关产品推荐
相关产品推荐

