【问题标题】:Get text, which goes after span element, not including the text that is before the span, using jquery使用jquery获取文本,它在span元素之后,不包括span之前的文本
【发布时间】:2018-12-27 19:53:37
【问题描述】:

我有这个 HTML 代码:

<div>
    <span>
        First text
        <span class="dot"></span>
        Second text
    </span>
    <span class="other-span">
    </span>
</div>

我只需要第二个文本。我试过这个 JQuery 代码:

const a = $('div').find('span:nth-child(1)').text();
console.log(a);

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

First text  Second text

正确的做法应该是在 span 元素之后仅获得 Second textdot

【问题讨论】:

  • second text放在span标签里面然后试试
  • @Xzandro nope,这略有不同,上述问题的解决方案只是检查类型文本,但在这里如果我使用它,它会返回我两个 第一个文本第二个文本
  • @vinaykumarreddy 我无法修改html 代码
  • const a = $('div span').contents().eq(2).text(); 嗯,有点不一样,是的,但是背后的思路基本一样。

标签: javascript jquery html


【解决方案1】:

你可以得到 HTML 然后像这样剥离文本:

const a = $('div').find('span:nth-child(1)').html().split('<span class="dot"></span>')[1];
console.log(a.trim());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <span>
        First text
        <span class="dot"></span> Second text
  </span>
  <span class="other-span">
    </span>
</div>

【讨论】:

  • 非常感谢!!
【解决方案2】:

您可以使用nodeType 属性。我希望下面的例子会有所帮助,

const a = $('div').find('span:nth-child(1)').contents().filter(function() {
  return this.nodeType == 3;
})[1]
console.log(a.textContent.trim());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <span>
        First text
        <span class="dot"></span> Second text
  </span>
  <span class="other-span">
    </span>
</div>

【讨论】:

  • 非常感谢您的解决方案,但由于某些原因 .textContent 为我返回 undefined :(
  • @DashaRee 好的。你检查过上面的sn-p吗?这工作正常吗?
猜你喜欢
  • 2011-10-18
  • 1970-01-01
  • 2023-03-16
  • 2018-10-28
  • 2014-07-17
  • 1970-01-01
  • 1970-01-01
  • 2021-02-14
  • 2019-12-23
相关资源
最近更新 更多