【问题标题】:How to add HTML tags around text contents?如何在文本内容周围添加 HTML 标签?
【发布时间】:2017-04-02 06:20:17
【问题描述】:

我有一个带有 2 个或更多标签的段落:

<p>#tag1 #tag2</p>

现在我想找到所有标签并像这样包装它们:

<p><span class="someClass">#tag1</span> <span class="someClass">#tag2</span></p>

【问题讨论】:

    标签: javascript jquery replace find


    【解决方案1】:

    您可以将.html() 与传递当前值的回调一起使用并使用正则表达式:

    #\w+\b
    

    这意味着:匹配任何以#开头的单词

    $("p").html(function(index, html) { 
            return html.replace(/(\#\w+\b)/g, "<span>$1</span>") 
           });
                
    span { color: orange }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p>#tag1 #tag2</p>
    <p>Here's another #tag3</p>

    【讨论】:

      【解决方案2】:

      $('p:contains("#")').each(function() {
          var tags = $(this).text().split(' ');
          var wrapped_tags = '';
      
          tags.forEach(function(tag) {
            wrapped_tags += '<span class="someClass">'+tag+'</span> ';
          });
      
          $(this).html(wrapped_tags);
      });
      .someClass {
        color:red;
      }
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <p>#tag1 #tag2</p>

      【讨论】:

      • 这也将包装非“标签”(虽然问题中不清楚是否只有标签或混合)
      • @freedomn-m 是的,我认为 op 意味着有很多 pharagraps,其中一些只有标签
      • @freedomn-m 反正你的答案更好
      • @Sojtin 谢谢,但总有循环版本的余地。一些 jquery 命令(比如这里的 map 和 html(callback) 以及正则表达式)可能不太明显,并且有一个更明确的版本可能是有益的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-06
      • 2016-01-28
      • 2021-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多