10

我在 dom 中有一张看起来像这样的桌子

<div id="table">
<table>
<tr>
  <td>a</td>
  <td>b</td>
  <td>c</td>
  <td>d</td>
</tr>
<tr>
  <td>a</td>
  <td>b</td>
  <td>c</td>
  <td>d</td>
</tr> 
</div>

我想遍历这个表,比如$('#table').each(function(){})但我只想遍历第二列。所以本例中的值为 b。

任何想法如何做到这一点?

谢谢!

4

3 回答 3

28

试试这个:

$("table tr td:nth-child(2)").each(function () {

});
于 2013-01-24T03:30:14.713 回答
12

使用nth-childjQuery 中的选择器,这应该可以工作:

$("#table").find("td:nth-child(2)").each(function () {

});

这使用nth-child选择器http://api.jquery.com/nth-child-selector/,作为链接状态,它将选择作为<td>其父级的第二个子级的所有元素(这将是 a <tr>)。

这是一个演示它的小提琴:http: //jsfiddle.net/GshRz/

如果您正在寻找一个选择器来获取<td>仅在表中立即出现的 s(例如不在嵌套表中),请使用以下内容:

$("#table").children("tbody").children("tr").children("td:nth-child(2)").each(function () {

});

http://jsfiddle.net/GshRz/1/

根据您的结构(可能包括 a <thead>),您可以使用.children("thead, tbody")而不是仅使用.children("tbody").

此外,如果您想抓取几列,选择<tr>元素然后获取它们的子<td>元素可能会更容易。例如:

$("#table1").children("tbody").children("tr").each(function (i) {
    var $this = $(this);
    var my_td = $this.children("td");
    var second_col = my_td.eq(1);
    var third_col = my_td.eq(2);
    console.log("Second Column Value (row " + i + "): " + second_col.html());
    console.log("Third Column Value (row " + i + "): " + third_col.html());
});

http://jsfiddle.net/GshRz/2/

您使用什么选择器以及在哪里使用取决于表格的结构和内容。所以请记住区分childrenandfindnth-childand eq

于 2013-01-24T03:28:54.360 回答
1
$("#table td:nth-child(2)").each(function (index) {
   alert('Row no. ' + (index+1) + ', Column 2 : ' + $(this).html());
});

样本

于 2013-01-24T03:35:04.197 回答