2011-03-03 90 views
2

這裏是我的代碼片段:CSS選擇 - 選擇特定的子元素

<div class="totals"> 
     <table id="shopping-cart-totals-table"> 
    <col /> 
    <col width="1" /> 
    <tfoot> 
     <tr> 
    <td style="" class="a-right" colspan="1"> 

     <strong>Grand Total</strong> 
    </td> 
    <td style="" class="a-right"> 
     <strong><span class="price">$364.99</span></strong> 
    </td> 
</tr> 
    </tfoot> 
    <tbody> 

     <tr> 
    <td style="" class="a-right" colspan="1"> 
     Subtotal </td> 
    <td style="" class="a-right"> 
     <span class="price">$354.99</span> </td> 
</tr> 
<tr> 
    <td style="" class="a-right" colspan="1"> 

     Shipping & Handling (Flat Rate - Fixed) </td> 
    <td style="" class="a-right"> 
     <span class="price">$10.00</span> </td> 
</tr> 
    </tbody> 
</table> 

有沒有一種方法來選擇顯示「10.00 $」的跨度?也許選擇元素的第二次出現? I.E .:第二次出現「.totals table tbody tr td [colspan ='']」?

+2

請記住編碼您'&'字符('&')。 – 2011-03-03 20:32:07

回答

8

隨着CSS3的:nth-child()很容易滿足「特定」的標準:

#shopping-cart-totals-table > tbody > tr:nth-child(2) > td:nth-child(2) .price 

或者是工作更有利於瀏覽器的兼容性(中不使用CSS3選擇器的替代,假設正好有兩個tr秒和2 td S):

#shopping-cart-totals-table > tbody > tr + tr > td + td .price 
+0

你不需要在''span結尾添加'span'嗎? – 2011-03-03 20:30:00

+0

@Chris:我錯過了,謝謝。 – BoltClock 2011-03-03 20:32:10

1

如果你有改變購物車的輸出的能力,你可以添加一個類的<tr>標籤,如<tr class="row01"><tr class="row02">

如果你不能改變你的後端,那麼這是一個前端技術的選擇。最跨瀏覽器的方法是使用jQuery來應用行類。另一種替代方案CSS3不受任何當前IE支持;鑑於這是購物車,您可能對最廣泛的瀏覽器支持感興趣。

喜歡的東西:

$('#shopping-cart-totals-table tr').each(function(n){ 
    $(this).addClass('row'+n); 
}); 

或者,如果你只是在第三個項目感興趣,使用jQuery以同樣的方式爲CSS3:

$('#shopping-cart-totals-table tr:nth-child(2) .price').addClass('highlightClass');