我有这个 html:
<span class="price">
$61.00
<span class="detailFreeShipping">With Free Shipping</span>
</span>
如何编写一个只给我价格文本“$61.00”的 jquery 选择器?
我想让它尽可能通用,因为在某些情况下可能没有内部跨度,只有父跨度。
最佳答案
你可以这样做:
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();
}
});
那么你可以这样调用它
var price = $(".price").textOnly();
你会得到你想要的值(value)。
关于javascript - 如何只选择顶部元素文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/906503/