替换后,innerHTML无法呈现 [英] innerHTML not rendering after replace
问题描述
我正在尝试使某些单词在页面中突出显示.为此,我想查找所有文本节点,并仅将特定单词替换为将其突出显示的跨度.该代码似乎可以正确搜索并在文本节点中找到单词,但是替换无效.我明白了:
I am trying to get certain words to highlight in a page. To accomplish this, I want to find all text nodes and replace only the specific word with a span that will highlight it. The code appears to search and find the words in the text nodes properly, but the replace is not working. I get this:
< span style ="background-color:#FBC300;"> foo</span>
<span style="background-color: #FBC300;">foo</span>
我想得到这个:
foo(背景突出显示)
And I want to get this:
foo (with a highlighted background)
function toRegExp(text) {
return new RegExp(text, 'g');
}
function toSpan(text) {
return '<span style="background-color: #FBC300;">' + text + '</span>';
}
function replaceText(squery, node) {
node = node || document.getElementById("mainContent"); // base node
for (node=node.firstChild;node;node=node.nextSibling){
if (node.nodeType==3) {
if (node.innerHTML) {
node.innerHTML = node.innerHTML.replace(toRegExp(squery), toSpan(squery));
} else { // support to IE
node.nodeValue = node.nodeValue.replace(toRegExp(squery), toSpan(squery));
}
}
else replaceText(squery, node);
}
}
推荐答案
文本节点不能包含元素,因此您需要将文本节点拆分为多个节点.例如,如果要突出显示hello world
中的world
,则需要将其拆分为文本节点hello
和元素<span>world</span>
,然后可以对其进行样式设置.像这样:
A text node can't contain elements, so you'll need to take the text node and split it into multiple nodes. For example, if you want to highlight world
in hello world
, you'll need to split it into a text node hello
and an element <span>world</span>
, which you can then style. Something like this:
function replaceText(squery, node) {
node = node || document.getElementById("mainContent"); // base node
for (node = node.firstChild; node; node=node.nextSibling) {
if (node.nodeType == 3 && node.nodeValue) {
var pieces = node.nodeValue.split(squery);
if (pieces.length > 1) {
// Split this node up into pieces
for (var i = 0; i < pieces.length - 1; i++) {
node.parentNode.insertBefore(document.createTextNode(pieces[i]), node);
var span = document.createElement('span');
span.style.backgroundColor = '#FBC300';
span.innerText = squery;
node.parentNode.insertBefore(span, node);
}
node.nodeValue = pieces[pieces.length - 1];
}
}
else
replaceText(squery, node);
}
}
这篇关于替换后,innerHTML无法呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!