将非 html 文本封装在 html 文档中

Encapsulate non html text in an html document

本文关键字:html 文档 封装 文本 将非      更新时间:2023-09-26

我需要创建一种方法来将所有非html单词封装在带有html的html页面中。举个例子:

<p id="paragraph"><a href="http://www.google.com">Google it!</a>But I <b>must</b> explain to you</p> 

应改为

<p id="paragraph"><a href="http://www.google.com"><span id="word1">Google</span> <span id="word2">it!</span></a><span id="word3">But</span> <span id="word4">I</span> <b><span id="word5">must</span></b> <span id="word6">explain</span> <span id="word7">to</span> <span id="word8">you</span></p> 

我试图提取所有单词:

group_text = $("#paragraph").text().trim().split(" ");

然后用选定的 HTML 封装每个单词,但这会删除文档可能具有的所有其他现有 HTML

for (var it = 0; it < group_text.length; it++) {
    group_text[it] = $('<span/>', {
        id: 'word' + (it+1),
        html: group_text[it]
    }).append(" ");
}

任何可能真正有效的解决方案?

您需要编写递归函数来处理嵌套文本。也许是这样的:

function wrap($node) {
    $node.contents().each(function() {
        if (this.nodeType === 3) {
            $(this).replaceWith(this.nodeValue.trim().split(/'s+/).map(function(el) {
                return '<span class="word' + ++i + '">' + el + '</span>';
            }));
        }
        else if (this.nodeType === 1) {
            wrap($(this));
        }
    });
}
var i = 0;
wrap($('#paragraph'));
alert($('#paragraph').html())
span {
    border-bottom: 1px dashed #AAA;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="paragraph"><a href="http://www.google.com">Google it!</a>But I <b>must</b> explain to you</p>

如果节点类型3则需要将文本拆分为单个单词,并将每个单词包装到范围中。如果节点类型为 1 ,则这是元素节点, - 再次调用wrap函数。