【问题标题】:CSS Selectors - Selecting a specific child elementCSS 选择器 - 选择特定的子元素
【发布时间】:2011-08-25 10:46:04
【问题描述】:

这是我的代码 sn-p:

<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”的跨度?也许选择第二次出现的元素? IE:第二次出现“.totals table tbody tr td[colspan='']”?

【问题讨论】:

  • 请记住编码你的&amp;amp;字符(&amp;amp;)。

标签: css css-selectors


【解决方案1】:

使用 CSS3 的 :nth-child() 很容易满足“特定”标准:

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

或者,一种更利于浏览器兼容性的替代方案(不使用 CSS3 选择器,假设正好有两个 trs 和两个 tds):

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

【讨论】:

  • 不需要在后面加上span吗?
【解决方案2】:

如果你有能力改变购物车的输出,你可以给&lt;tr&gt;标签添加一个类,例如&lt;tr class="row01"&gt;&lt;tr class="row02"&gt;

如果你不能改变你的后端,那么它就是前端技术的选择。最跨浏览器的方法是使用 jQuery 来应用行类。任何当前的 IE 都不支持另一种选择 CSS3。鉴于这是一个购物车,您可能对最广泛的浏览器支持感兴趣。

类似:

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

或者,如果您只对第三项感兴趣,可以像 CSS3 一样使用 jQuery:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-23
    相关资源
    最近更新 更多