Javascript 在 jQuery 中遍历表中的第二列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14493423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterate through second columns in a table in jQuery
提问by dzm
I have table in the dom that looks like this
我在 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>
I want to iterate through this table, such as $('#table').each(function(){})but I only want to iterate through the second column. So the ones which in this example have a value of b.
我想遍历这个表,例如$('#table').each(function(){})但我只想遍历第二列。所以在这个例子中的值是 b。
Any ideas how to do this?
任何想法如何做到这一点?
Thank you!
谢谢!
回答by phnkha
Try this:
尝试这个:
$("table tr td:nth-child(2)").each(function () {
});
回答by Ian
Using the nth-childselector in jQuery, this should work:
使用nth-childjQuery 中的选择器,这应该可以工作:
$("#table").find("td:nth-child(2)").each(function () {
});
This uses the nth-childselector, http://api.jquery.com/nth-child-selector/, which as the link states, would select all <td>elements that are the 2nd child of their parent (which would be a <tr>).
这使用nth-child选择器http://api.jquery.com/nth-child-selector/,作为链接状态,它将选择作为<td>其父级(将是<tr>)的第二个子级的所有元素。
Here's a fiddle that demonstrates it: http://jsfiddle.net/GshRz/
这是一个演示它的小提琴:http: //jsfiddle.net/GshRz/
If you are looking for a selector that gets the <td>s that are only immediately in the table (like not in a nested table), then use something like:
如果您正在寻找一个选择器来获取<td>仅在表中立即出现的s(例如不在嵌套表中),则使用以下内容:
$("#table").children("tbody").children("tr").children("td:nth-child(2)").each(function () {
});
Depending on your structure (where you might include a <thead>), you could use .children("thead, tbody")instead of just .children("tbody").
根据您的结构(您可能在其中包含<thead>),您可以使用.children("thead, tbody")而不仅仅是.children("tbody").
Also, in case you want to be grabbing several columns, it could be easier to select the <tr>elements and then get their children <td>elements. For example:
此外,如果您想抓取多列,选择<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());
});
What selectors you use and where, is up to the structure and content of your table. So remember to differentiate between childrenand find, and nth-childand eq.
您使用什么选择器以及在哪里使用,取决于表格的结构和内容。所以请记住区分childrenandfind和nth-childand eq。

