我有以下标记:
<table>
<thead>
...
</thead>
<tbody>
<tr>
<td>
<span class='select_me' id='42'></span>
</td>
<td>
<span class='select_me' id='43'></span>
</td>
</tr>
<tr>
<td>
<span class='select_me' id='50'></span>
</td>
<td>
<span class='select_me' id='54'></span>
</td>
</tr>
</table>
如何在每一行中选择第二个或第一个“select_me”? 我觉得它是这样的 - 我想获得id
$("td").each(function(){
v = $(this).children(".select_me:first").attr("id");
});
但输出'undefined',任何帮助都将不胜感激
答案 0 :(得分:7)
您可以使用:eq选择器:
$("tr").each(function() {
var firstId = $("span.select_me:eq(0)", this).attr("id");
var secondId = $("span.select_me:eq(1)", this).attr("id");
});
由于每行只有两个<span>
元素,因此您还可以使用:first和:last选择器:
$("tr").each(function() {
var firstId = $("span.select_me:first", this).attr("id");
var secondId = $("span.select_me:last", this).attr("id");
});
答案 1 :(得分:2)
首先 -
$("tr").each(function(){
v = $(this).find("td:nth-child(1) span.select_me").attr("id");
});
第二个 -
$("tr").each(function(){
v = $(this).find("td:nth-child(2) span.select_me").attr("id");
});
答案 2 :(得分:1)
试试这个 -
$("td").each(function(){
first = $(this).find("span.select_me:eq(0)").attr("id");// for first
Second = $(this).find("span.select_me:eq(1)").attr("id");// for second
});
答案 3 :(得分:1)
n-child可能有所帮助:http://api.jquery.com/nth-child-selector/
$("tr td:nth-child(2) span.select_me").attr('id')