2013-10-29 40 views
0

好日子,重構jquery使用find()查找特定元素

這不是一個真正的問題。但我只想知道是否有另一種方法來查找特定元素的值。所以我在這裏有一個樣本。

<table class="test"> 
    <thead>..</thead> 
    <tfoot>..</tfoot> 
    <tbody> 
    <tr> 
     <td class="foo>1<td> 
     <td class="foo>7<td> 
     <td class="foo>1<td> 
    </tr> 
    </tbody> 
</table> 

<table class="test"> 
    <thead>..</thead> 
    <tfoot>..</tfoot> 
    <tbody> 
    <tr> 
     <td class="foo>1<td> 
     <td class="foo>3<td> 
     <td class="foo>2<td> 
    </tr> 
    </tbody> 
</table> 

<table class="test"> 
    <thead>..</thead> 
    <tfoot>..</tfoot> 
    <tbody> 
    <tr> 
     <td class="foo>5<td> 
     <td class="foo>1<td> 
     <td class="foo>3<td> 
    </tr> 
    </tbody> 
</table> 

我的解決辦法:

$("table.test").each(function() { 
    alert($(this).find("td.foo:first").text()); 
}); 

所以這會提醒每個表的所有第一<td class="foo">

我想知道是否有另一種方法來做到這一點。

感謝

回答

1

您可以使用.find()

$("table.test").find("td.foo:first").each(function() { 
    alert($(this).text()); 
}); 

演示:Fiddle

+0

喔,所以你可以鏈這樣的事情。謝謝。它確實有幫助。有一個問題,如果你像這樣鏈接'$(this)'會引用最後一個選擇器? –

+1

@BoyPasmo'this'裏面的'each'將引用正在迭代的dom元素,在這種情況下'td.foo:first'元素 –

+0

謝謝。它真的清除了我腦海中的混亂。 –