【问题标题】:Add a span to a substring / part of text向子字符串/部分文本添加跨度
【发布时间】:2018-05-15 03:09:38
【问题描述】:

我需要在“8:00”左右创建一个跨度,以便更改其颜色。显然我无法编辑实际的 html。

<span class="foo">The time is 8:00</span>

我能够在正确的位置拆分它:

var justTheTime= $('.foo').text().split('The time is')[1]; 

但不知道如何在它周围添加跨度。帮忙?

var withStyles = $('<span style="color:red">'+onlyTheDate+'</span>');
$(".foo").replace(justTheTime,withStyles);

【问题讨论】:

    标签: javascript jquery replace split var


    【解决方案1】:

    .replace() 不是 jQuery 函数;它是一个 JavaScript 的。此外,您似乎正在尝试添加一个未定义的变量 onlyTheDate 而不是 justTheTime - 我已经在我的示例中更正了这一点。

    您可以做的是使用 replaceWith(),然后手动在时间之前插入文本。请注意,您需要将 The time is 包装在自己的 &lt;span&gt; 中:

    var justTheTime = $('.foo').text().split('The time is')[1];
    var withStyles = $('<span>The time is</span><span style="color:red">' + justTheTime + '</span>');
    $('.foo').replaceWith(withStyles);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <span class="foo">The time is 8:00</span>

    希望这会有所帮助:)

    【讨论】:

      【解决方案2】:

      您可以查找格式为时间的字符串/(\d{1,2}):(\d{1,2})/g,这将用颜色替换所有项目,因此如果您有多个日期,它将全部替换,而不仅仅是这样的:

      $('.foo').html(
          $('.foo').text().replace(/(\d{1,2}):(\d{1,2})/g, '<span class="red">$1:$2</span>')
      )
      .red {color: red;}
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <span class="foo">The time is 8:00</span>

      【讨论】:

        【解决方案3】:

        replace() 方法作用于字符串,而不是 jQuery 元素。

        用正则表达式替换span的内容,用.html()更新。

        $('.foo').html(function(i, oldtext) {
            return oldtext.replace(/The time is (.*)/, 'The time is <span style="color:red">$1</span>');
        });
        

        【讨论】:

          【解决方案4】:

          尝试类似:

          var justTheTime = $('.foo').text().split('The time is')[1];
          var spanText = "The time is <span style='color:red'>"+ justTheTime +"</span>";
          $('.foo').html(spanText);
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
          <span class="foo">The time is 8:00</span>

          【讨论】:

            猜你喜欢
            • 2010-09-12
            • 2016-06-09
            • 2018-08-31
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-01-23
            • 2011-10-20
            相关资源
            最近更新 更多