如何只选择顶部元素文本?

Amr*_*rhy 6 html javascript jquery

我有这个HTML:

<span class="price">
        $61.00
          <span class="detailFreeShipping">With Free Shipping</span>
    </span>
Run Code Online (Sandbox Code Playgroud)

如何编写一个jquery选择器,只给我"$ 61.00"的价格文本?

我想让它尽可能通用,因为在某些情况下可能没有内部跨度,只有父内部.

Nic*_*rdi 11

你可以这样做:

jQuery.fn.extend({
    textOnly: function() {
        // make a clone of this object so we are not changing the actual DOM
        var obj = $(this).clone();

        // remove all the children, i.e. any DOM objects
        obj.children().remove();

        // get the text value after all DOM elements are removed
        return obj.text();
    }
});
Run Code Online (Sandbox Code Playgroud)

然后你就可以这样称呼它

var price = $(".price").textOnly();
Run Code Online (Sandbox Code Playgroud)

你会得到你想要的价值.