【问题标题】:How to cut string after certain HTML tag?如何在某些 HTML 标记后剪切字符串?
【发布时间】:2017-06-13 07:16:44
【问题描述】:

我想在</b>标签之后剪切文本。

例如,

<div class="quote"><b> Quote from: Bob </b>
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.</div>

应该被截断为

<div class="quote"><b> Quote from: Bob </b>

我该如何存档?

这是我想出的:

https://jsfiddle.net/Babr/2q4940h1/8/

【问题讨论】:

  • 为什么不直接使用$(".quote b").text()
  • 您的问题似乎不完整。你应该告诉我们:当里面没有&lt;b&gt;标签,当它里面有超过1个&lt;b&gt;标签,当它里面有其他标签但没有&lt;b&gt;s时,这是如何修剪的。跨度>

标签: javascript jquery truncate


【解决方案1】:

对于您的情况,您可以这样做:

$(".quote").html($(".quote").children());

将被截断为:

<div class="quote"><b> Quote from: Bob </b></div>

FIDDLE

【讨论】:

    【解决方案2】:

    过滤掉div内的文本节点并移除它们。

    $('.quote')
      // get all child nodes
      .contents()
      // filter out text nodes
      .filter(function() {
        return this.nodeType === 3;
      })
      // remove them
      .remove()
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="quote"><b> Quote from: Bob </b> It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.</div>

    或使用带有回调的html() 方法将HTML 内容替换为b 标签元素。

    $('.quote').html(function() {
      // return the inner b tag
      return $(this).find('b');
      // or you just want to remove the text nodes then 
      // get all elements using $(this).children()
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="quote"><b> Quote from: Bob </b> It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.</div>

    【讨论】:

      【解决方案3】:

      类似的东西。

      var bTag = $(".quote").find("b");
      var textThatMatters = bTag.text() + ' reads more...';
      bTag.text(textThatMatters)
      $(".quote").empty().append(bTag);
      

      这里是jsFiddle

      【讨论】:

        【解决方案4】:

        另一种选择

        $('.quote').children('b').text()
        

        【讨论】:

          猜你喜欢
          • 2014-07-21
          • 1970-01-01
          • 2014-01-17
          • 2012-08-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-14
          相关资源
          最近更新 更多