【问题标题】:Get the text after span element using jquery使用 jquery 获取 span 元素之后的文本
【发布时间】:2011-10-18 23:59:17
【问题描述】:

我有这个 html 代码

<div id="mydiv">
    <div>
        <span>Text inside span</span>
        Text next to span
    </div>
    <div>
        Contents inside the 2nd div element...
    </div>
</div>

我想获得“跨度旁边的文本”。我试过这段代码 JQuery 代码

var a = $('#mydiv div').first().find('span').parent().text();
alert(a);

上面jquery代码的输出是这样的:

Text inside span
Text next to span

仅获取“跨度旁边的文本”应该怎么做?

【问题讨论】:

标签: jquery


【解决方案1】:
var a = $('#mydiv div').first().contents().filter(function() {
    return this.nodeType == 3;
}).text();

这会获取所选div 的内容,并过滤匹配的集合,只返回带有nodeType == 3 的元素,它们是文本节点。

【讨论】:

    【解决方案2】:

    使用此代码:

     $('#myDiv')
      .contents()
      .filter(function() {
        return this.nodeType == Node.TEXT_NODE;
      }).text();
    

    【讨论】:

    • 最好使用nodeType == 3而不是TEXT_NODE常量,IE不支持。
    • @James 谢谢,我不知道 nodeType 的整数值
    【解决方案3】:

    我是这样理解的:

    $('#mydiv div').first().contents().eq(1).text();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-14
      • 1970-01-01
      • 2013-12-21
      • 1970-01-01
      • 2019-12-23
      • 1970-01-01
      • 2012-11-03
      • 2018-10-28
      相关资源
      最近更新 更多