将非 html 文本封装在 html 文档中
Encapsulate non html text in an html document
我需要创建一种方法来将所有非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
函数。
相关文章:
- HTML文档中脚本标记的位置-<头部>&<身体>有不同的行为
- 如何用javascript重写html文档
- 是否可以使用有角度的HTML文档进行$编译
- 如何确保通过电子邮件发送的html文档中的Google Drive链接不会被识别为附件
- 将jQuery.js文件附加到html文档中
- 为任意html文档创建不引人注目的覆盖
- 在HTML文档中使用XML文件中的数据
- 删除“;NaN”;来自HTML文档
- 显示“<script src='some.js'></脚本>"在Html文档中
- 如何通过JS在不干扰其标记的情况下更改HTML文档中字符串的所有实例
- 如果iframe在src(pdf或text)中有非html文档,则iframe中的onload不起作用
- 如何从 html 文档中调用 yahoo weather api javascript 函数
- c# mvc nreco HtmlToPdfConverter 问题将 html 文档转换为 pdf
- 访问 HTML 文档中的 HTML
- 使用 PHP 将 css/js 文件分配给 html 文档
- 将变量从服务器上的外部文件加载到 HTML 文档中
- 使用 ajax 将 HTML 文档附加到元素
- 如何将 HTML 文档作为起始值传递给 CodeMirror
- 如何在父 html 文档中访问嵌入的 html 文档的子级
- 无法将我的 html 文档连接到 jquery