dzm*_*dzm 9 html javascript jquery dom
我在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>
Run Code Online (Sandbox Code Playgroud)
我想迭代这个表,例如$('#table').each(function(){})但我只想迭代第二列.所以在这个例子中具有b值的那些.
任何想法如何做到这一点?
谢谢!
phn*_*kha 24
试试这个:
$("table tr td:nth-child(2)").each(function () {
});
Run Code Online (Sandbox Code Playgroud)
Ian*_*Ian 11
nth-child在jQuery中使用选择器,这应该工作:
$("#table").find("td:nth-child(2)").each(function () {
});
Run Code Online (Sandbox Code Playgroud)
这使用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 () {
});
Run Code Online (Sandbox Code Playgroud)
根据您的结构(您可能包含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());
});
Run Code Online (Sandbox Code Playgroud)
您使用的选择器和位置取决于表的结构和内容.所以请记住区分children和find,nth-child和eq.