【问题标题】:jquery selectors - do not select inner elements [duplicate]jquery选择器 - 不要选择内部元素[重复]
【发布时间】:2015-08-29 02:21:07
【问题描述】:

可能重复:
Getting text within element excluding decendants

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

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

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

例如,如果我做div.price.text(),我会得到两个价格。所以“一行”是指div.price.not("span.old_price").text() 或类似的东西。

【问题讨论】:

    标签: javascript jquery css-selectors


    【解决方案1】:

    来自 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() 包装上述代码

    【讨论】:

    • 正如我所说,我只需要使用选择器执行它,我不能使用函数等。
    • @ItayD 选择器本质上是一个函数,至少在您可以创建自己的选择器的范围内。所以我看不出这个限制的意义
    猜你喜欢
    • 2011-08-14
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    • 2019-05-21
    • 2015-01-17
    • 1970-01-01
    相关资源
    最近更新 更多