【问题标题】:Get Text from h3 element without getting text from child elements of h3从 h3 元素获取文本而不从 h3 的子元素获取文本
【发布时间】:2012-05-25 15:14:58
【问题描述】:

这就是我想要的:

<h3 class="ExpressCheckoutTitle">
            <a onclick="" href="#" class="ChangeLink">Modify »</a>
            Step 4: Order Confirmation
  </h3>

我只想获取文本“第 4 步:订单确认”

$('h3.ExpressCheckoutTitle').text() 给了我来自&lt;a&gt; 元素的文本,如下所示:“修改 >> 第 4 步:订单确认”

我如何在 jquery 中做到这一点?

【问题讨论】:

标签: jquery


【解决方案1】:

您可以使用contents() 直接访问文本节点。试试这个:

var text = $("h3").contents().filter(function() {
    return this.nodeType == 3;
});

Example fiddle

【讨论】:

  • 我一直忘记contents 将包含文本节点。
【解决方案2】:

我会使用.contents 并按nodeType == 3 过滤。见

var h3Text = $('h3.ExpressCheckoutTitle').contents().filter(function() {
   return this.nodeType == 3
}).text();

alert($.trim(h3Text));

DEMO

编辑:在使用 $.trim 删除尾随空格后更新.. 并且还正确使用了过滤器

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-12
    • 2019-05-15
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    • 2016-02-29
    • 1970-01-01
    相关资源
    最近更新 更多