我有一个问题,过去 2 天我一直在尝试解决,但无法解决。
问题:
我有一个 HTML 作为
<div class="string-box">
Text 1 wrap me
<span class="inner-span">Don't search me</span>
<span class="inner-span">Identical text</span>
Identical text
substring match
<span class="inner-span">Don't search substring match</span>
<br>
Finally wrap me
</div>
我要包装的内容有下面
<div class="string-box">
<span> Text 1 wrap me </span>
<span class="inner-span">Don't search me</span>
<span class="inner-span">Identical text</span>
<span>Identical text</span>
<span>substring match</span>
<span class="inner-span">Don't search substring match</span>
<br>
<span>Finally wrap me</span>
</div>
我尝试过的
a) 我首先尝试在 html 中搜索字符串并使用字符串替换将字符串替换为包装字符串。 这种方法的问题在于它也替换了 child 中的东西..
b) 我尝试克隆节点并删除所有子节点,但后来我迷失了字符串的位置。
c) 我尝试了以下代码来替换 textNode,但我最终得到的是 HTML
$('.string-box').contents().filter(function(){
return this.nodeType == 3;
}).each(function(){
this.nodeValue = '<span>'+this.nodeValue+'</span>';
})
在此先感谢您的时间和帮助..
最佳答案
您的代码很接近,但是 nodeValue
不能包含 HTML - 因此它在您的尝试中被编码。相反,您可以 wrap()
HTML 中的 textNode,如下所示:
$('.string-box').contents().filter(function() {
return this.nodeType == 3;
}).each(function() {
$(this).wrap('<span />');
})
更新
这里修复了 nodeValue 包含换行符的情况,并且您想将节点的每一行都包装在自己的 span
中:
$('.string-box').contents().filter(function() {
return this.nodeType == 3 && this.nodeValue.trim();
}).each(function() {
var $spans = this.nodeValue.trim().split(/\r?\n/).map(function(i, v) {
return $('<span />', { text: i + ' ' });
});
$(this).replaceWith($spans);
})
关于javascript - 用 div 包装文本,不包括所有子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38521798/