0

可能重复:
在不包括后代的元素中获取文本

我正在尝试使用 1 个选择器并且仅通过 text() 方法获取元素数据的一部分。假设我有以下 html 代码:

<div class="price">
     <span class='old_price'>1150</span><br />
     920 
</div>

在这种情况下,我只想得到920(没有 t 1150)。是否可以使用一个选择器来做到这一点?

例如,如果我这样做div.price.text(),我会得到两个价格。因此,我所说的“一条线”是指div.price.not("span.old_price").text()或类似的意思。

4

1 回答 1

0

来自 jQuery API 文档Description: Get the combined text contents of each element in the set of matched elements, including their descendants.,因此即使您只选择外部元素,您也会使用 text(); 获得两个数字作为结果的一部分;

所以你想要的是过滤掉除文本节点之外的所有内容

$(".price").contents().filter(
    function() {
       return this.nodeType === 3;  // text node
    }
).text();

您可能想要修剪空白(在这种情况下,您可以用$.trim()

于 2012-07-22T14:24:01.707 回答