求统计HTML表格中非空行的JavaScript实现代码
统计HTML表格非空行的JavaScript方案
要实现仅统计表格中的非空行(跳过所有单元格均为空的行),可以通过filter()方法对表格行进行过滤,判断每行是否包含有效内容。以下是修改后的完整代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ // 过滤掉所有单元格均为空的行 var nonEmptyRows = $("#myTable tr").filter(function() { // 获取当前行所有单元格的文本,去除首尾空格 var rowText = $(this).find("td, th").text().trim(); // 文本不为空则保留该行 return rowText !== ""; }); var rowCount = nonEmptyRows.length; alert(rowCount); // 输出:4 }); }); </script> </head> <body> <table id="myTable" border="1" width="140"> <tr> <th>ID</th> <th>Name</th> <th>Age</th> </tr> <tr> <th></th> <th></th> <th></th> </tr> <tr> <td>1</td> <td>John</td> <td>25</td> </tr> <tr> <th></th> <th></th> <th></th> </tr> <tr> <td>2</td> <td>Peter</td> <td>18</td> </tr> <tr> <td>3</td> <td>Harry</td> <td>14</td> </tr> </table> <br> <button type="button">Get Number of Rows</button> </body> </html>
关键逻辑说明
- 过滤空行:通过
filter()遍历所有<tr>,对每行执行判断:- 用
find("td, th")获取该行所有单元格(兼容示例中混用<th>和<td>的情况) - 调用
text().trim()获取单元格文本并去除首尾空格,若结果为空字符串,说明该行所有单元格都是空的,将其过滤
- 用
- 统计有效行:过滤后得到的
nonEmptyRows就是所有包含内容的行,直接取其长度即可得到目标统计数
如果需要仅统计数据行(排除表头行),可以在过滤后额外移除表头:
// 移除第一个表头行 nonEmptyRows = nonEmptyRows.slice(1); var rowCount = nonEmptyRows.length; // 此时输出:3
内容的提问来源于stack exchange,提问作者arkady
相关产品推荐
相关产品推荐

