我无法用跨度包装html内容的每个单词,同时保留其他标记。
例如,如果我的代码示例是
<p><b>Lorem ipsum dolor sit amet</b><br/> <a href="#">consectetur</a> adipiscing elit. Nam nec scelerisque nisl, vitae mattis diam. Proin fermentum lorem in interdum porttitor.</p>
我想要做的是(代码也保留其他元素)
<p><b><span class="sc">Lorem</span> <span class="sc">ipsum</span> <span class="sc">dolor</span> <span class="sc">sit</span></b><br/> <span class="sc">amet</span> <a hre=""><span class="sc">consectetur</span></a> <span class="sc">adipiscing</span> <span class="sc">elit.</span> <span class="sc">Nam</span> <span class="sc">nec</span> <span class="sc">scelerisque</span> <span class="sc">nisl,</span> <span class="sc">vitae</span> <span class="sc">mattis</span> <span class="sc">diam.</span> <span class="sc">Proin</span> <span class="sc">fermentum</span> <span class="sc">lorem</span> <span class="sc">in</span> <span class="sc">interdum</span> <span class="sc">porttitor.</span></p>
我从Js代码中获得的是
<p><span class="sc">Lorem</span> <span class="sc">ipsum</span> <span class="sc">dolor</span> <span class="sc">sit</span> <span class="sc">amet</span> <span class="sc">consectetur</span> <span class="sc">adipiscing</span> <span class="sc">elit.</span> <span class="sc">Nam</span> <span class="sc">nec</span> <span class="sc">scelerisque</span> <span class="sc">nisl,</span> <span class="sc">vitae</span> <span class="sc">mattis</span> <span class="sc">diam.</span> <span class="sc">Proin</span> <span class="sc">fermentum</span> <span class="sc">lorem</span> <span class="sc">in</span> <span class="sc">interdum</span> <span class="sc">porttitor.</span></p>
正如您所看到的,我在输出中丢失了<b></b>, <br/> <a/>
标记标记。
我的Javacript代码,
var articleContent = "";
var totalWords = 0;
$("#content").find('p').each(function(){
var text = $(this).text().split(' ');
for( var i = 0, len = text.length; i<len; i++ ) {
text[i] = '<span class="sc">'+text[i]+'</span>';
}
totalWords = totalWords + i;
articleContent = articleContent + "<p>"+text.join(' ')+"</p>";
});//End of each ,
console.log(articleContent);
这是同一个JSfiddle
的小提琴如何在一个跨度中包装每个单词并保留其他标记?
我们可以假设我的HTML代码仅包含<b> </br> <a>
作为其他元素。
答案 0 :(得分:3)
试
$('p')
.find('*')
.addBack('p')
.each(function () {
textNode = $(this).contents().filter(function () {
return this.nodeType === 3; //Node.TEXT_NODE
});
text = textNode.text().split(' ');
replace = '';
$.each(text, function (index, value) {
if ( value.replace(/\s+/, "") ) { // Remove whitespaces
replace += '<span class="wraped">' + value + '</span>';
}
});
textNode.replaceWith( $(replace) );
});
答案 1 :(得分:2)
您正在使用正在剥离所有其他标记的.text()
。您将需要使用正则表达式执行此操作我认为,因为标记中有时会出现拆分('')找到的内容。
所以你需要一个正则表达式,它可以查找末尾有空格的字符串,或者标记及其结束标记。这不是直接的直截了当。这会查找空格:
text.replace(/(\w*)\s/g, "<span class="">$1</span> ")
答案 2 :(得分:0)
我相信这会对你有所帮助:
旧问题: Regex to match words in a paragraph but exclude inner HTML tags
从以下位置获取jQuery插件: http://jsfiddle.net/bfXPy/
您可以调用该功能
$("#content p").highlightText(/\b([a-z]+)\b/ig,"sc")
希望它能帮到你