【问题标题】:Iterate through second columns in a table in jQuery遍历jQuery中表中的第二列
【发布时间】:2023-04-06 11:49:01
【问题描述】:

我在 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。

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

谢谢!

【问题讨论】:

标签: javascript jquery html dom


【解决方案1】:

试试这个:

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

});

【讨论】:

  • 这也匹配主表中的任何嵌套表......所以一些td元素可以匹配多次。此外,您不需要tr 部分,因为td 始终是tr 的子级。当您使用 .find.children 之类的东西而不是用于 jQuery 解析的大选择器字符串时,它对 jQuery 来说更具可读性和更容易
【解决方案2】:

在 jQuery 中使用 nth-child 选择器,这应该可以工作:

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

});

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

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

如果您正在寻找一个选择器来获取仅在表中立即出现的&lt;td&gt;s(例如不在嵌套表中),请使用类似:

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

});

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

根据您的结构(可能包含&lt;thead&gt;),您可以使用.children("thead, tbody") 而不仅仅是.children("tbody")

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

$("#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/

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

【讨论】:

  • 感谢您的详细回复,我继续并选择了@namkha87,因为它有效并且似乎比 find() 更快
【解决方案3】:
$("#table td:nth-child(2)").each(function (index) {
   alert('Row no. ' + (index+1) + ', Column 2 : ' + $(this).html());
});

Sample

【讨论】:

    猜你喜欢
    • 2012-03-03
    • 2012-01-26
    • 1970-01-01
    • 2014-07-11
    • 2014-02-14
    • 2013-09-25
    • 2015-05-16
    • 1970-01-01
    相关资源
    最近更新 更多