jquery遍历table
遍历表格行与列
使用 each() 方法循环表格的行(tr)和单元格(td):
$("table tr").each(function() {
$(this).find("td").each(function() {
console.log($(this).text()); // 输出每个单元格内容
});
});
获取特定列数据
通过 eq(index) 选择指定列(索引从0开始):

$("table tr").each(function() {
const secondColumn = $(this).find("td").eq(1).text();
console.log(secondColumn); // 输出第二列内容
});
筛选带条件的行
结合 filter() 或条件判断筛选行:

$("table tr").filter(function() {
return $(this).find("td:first").text() === "目标值";
}).css("background-color", "yellow"); // 高亮符合条件的行
动态修改表格内容
遍历时修改单元格内容或属性:
$("table tr td").each(function() {
$(this).html("<b>" + $(this).text() + "</b>"); // 加粗文本
});
处理表头与数据行区分
使用 :header 选择器或 has() 方法:
$("table tr:not(:has(th))").each(function() {
// 仅遍历数据行(排除表头)
console.log($(this).find("td").text());
});
注意事项
- 确保DOM加载完成后执行代码,需包裹在
$(document).ready()中。 - 复杂表格可结合
closest()、parents()等方法定位特定区域。






