【问题标题】:Adding span to each word not in tag将跨度添加到不在标签中的每个单词
【发布时间】:2018-04-04 08:27:28
【问题描述】:

我需要一个实现以下目标的脚本: 在每个单词周围放置一个 span 标签,除了已经在标签中的单词。

例如下面的html:

<p>I <span>like</span> to go <b>to</b> the park.</p>

应该变成:

<p><span>I</span> <span>like</span> <span>to</span> <span>go</span> <b>to</b> <span>the</span> <span>park.</span></p>

到目前为止,我只成功地将句子片段放置在 span 标签中,但不是每个单词。 (使用此脚本:jsfiddle,允许使用 jQuery)

$("#tot")
    .contents()
    .filter(function () {
    // get only the text nodes
    return this.nodeType === 3 && this.nodeValue.trim() !== "";
}).wrap("<span />");
span {
    background:yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="tot">
I love to <span id="hello">go to</span> the park every <span>day</span> because <b>it is</b> fun.
</p>

非常感谢任何帮助。

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    给你:http://jsfiddle.net/oyb4adff/52/

    var result = $("#tot")
    .contents()
    .map(function () {
        // get only the text nodes
        var newText = "";
        if(this.nodeType === 3) {
          var text = this.nodeValue.trim().split(" ");
          for(var i=0; i<text.length; i++) {
            newText += "<span>" + text[i] + "</span>";
            if(i + 1 < text.length) newText += " ";
          }
          return newText;
        }
        return this.outerHTML;
    }).toArray()
    .join(" ");
    $("#tot").html(result);
    

    我所做的是:

    1. 循环浏览内容
    2. 如果是常规文本节点,则将其拆分为单独的单词
    3. 加上它们周围的跨度
    4. 如果它是一个 html 节点,那么只需将其重新添加而不进行编辑

    【讨论】:

      猜你喜欢
      • 2014-05-23
      • 2013-07-24
      • 1970-01-01
      • 1970-01-01
      • 2015-10-20
      • 2019-04-13
      • 2019-10-17
      • 1970-01-01
      • 2015-02-19
      相关资源
      最近更新 更多