2013-05-21 110 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")