jQuery选择器 - 选择特定标签内的文本

时间:2011-03-07 16:40:49

标签: javascript jquery css jquery-selectors css-selectors

这是我的代码段:

   <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>

我如何使用jQuery选择“价格”类的第一个范围,并将该标签中的“$ 364.99”文本分配给变量?

3 个答案:

答案 0 :(得分:3)

你可以这样做:

var price = $('span.price').first().text();

或者其中任何一个:

var price = $('span.price:first').text();
var price = $('span.price:eq(0)').text();
var price = $('span.price').eq(0).text();
var price = $($('span.price').get(0)).text();
var price = $($('span.price').get()[0]).text();

答案 1 :(得分:3)

var total = $('.price:first').text();

答案 2 :(得分:2)

获取文字

$(".price").eq(0).text()

设置文字

$(".price").eq(0).text('12.21$')