2013-05-21 139 views
13

我有这样的东西:jQuery选择每行的第一款TD

<table> 
    <tr> 
    <td>nonono</td> <!-- FIND THIS --> 
    </td>foobar</td> 
    </tr> 
    <tr> 
    <td>nonono2</td> <!-- FIND THIS --> 
    </td>foobar2</td> 
    </tr> 
    <tr> 
    <td>nonono3</td> <!-- FIND THIS --> 
    </td>foobar2</td> 
    </tr> 
</table> 

我与$('td:first')没有运气尝试;

预期回报:<td>nonono</td><td>nonon2</td>并提前<td>nonon3</td>

谢谢!

+0

从[文档】(http://api.jquery.com/first-selector/): *“':first'伪类相当于':eq(0)',它也可以写成::lt(1)'虽然这只匹配一个元素,但是::first-child可以匹配不止一个:每个父母一个。“* –

回答

28

您应该使用:first-child而不是:first

听起来你想通过他们进行迭代。你可以使用.each()来做到这一点。

例子:

$('td:first-child').each(function() { 
    console.log($(this).text()); 
}); 

结果:

nonono 
nonono2 
nonono3 

Alernatively,如果你不想重复:

$('td:first-child').css('background', '#000'); 

JSFiddle demo

+0

我会接受为正确答案,因为交替方法contais':first-child' –

6

试试这个选择 -

$("tr").find("td:first") 

演示-->http://jsfiddle.net/66HbV/

或者

$("tr td:first-child") 

演示-->http://jsfiddle.net/66HbV/1/

</td>foobar</td>应该是<td>foobar</td>

+0

只返回第一个td –

+1

只需使用'first-child'。':first'不能独立工作的原因是因为它拉动了第一个元素,而没有其他任何东西 –

+0

这是为我做的。寻找我使用的唯一一个:'$(this).find(“td:first”)' – Sander

1

尝试

var children = null; 
$('tr').each(function(){ 
    var td = $(this).children('td:first'); 
    if(children == null) 
     children = td; 
    else 
     children.add(td); 
}); 

// children should now hold all the first td elements 
1

$('td:first-child')将返回所需的元素的集合。

var text = $('td:first-child').map(function() { 
    return $(this).html(); 
}).get(); 
2

用途:

$("tr").find("td:first"); 

js fiddle - 这个例子有.text()上月底以表明它返回的元素。

备选地,可以使用:

$("td:first-child"); 

.find() - jQuery的API文档

2
var tablefirstcolumn=$("tr").find("td:first") 
alert(tablefirstcolumn+"of Each row")