【问题标题】:innerHTML not rendering after replace替换后innerHTML不呈现
【发布时间】:2020-04-10 18:29:00
【问题描述】:

我正在尝试在页面中突出显示某些单词。为此,我想查找所有文本节点并仅将特定单词替换为突出显示它的跨度。该代码似乎可以正确搜索并找到文本节点中的单词,但替换不起作用。我明白了:

foo

我想得到这个:
foo(带有突出显示的背景)

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);
  }
}

【问题讨论】:

  • 在创建 span 时,您需要使用真正的标签分隔符 (<>) 而不是 HTMLEntities。但是你不能在文本节点中设置 HTML。

标签: javascript replace innerhtml


【解决方案1】:

文本节点不能包含元素,因此您需要获取文本节点并将其拆分为多个节点。例如,如果您想在hello world 中突出显示world,则需要将其拆分为一个文本节点hello 和一个元素<span>world</span>,然后您可以对其进行样式设置。像这样的:

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);
    }
}

【讨论】:

  • 谢谢!这解决了问题并正确突出显示单词。
【解决方案2】:

对我来说,这是有效的:

<html>
    <body>       
        <p>bla test bla</p>
        <script>
            function highlight(text) {
                document.body.innerHTML = document.body.innerHTML.replace(text,'<span style="background-color:red">'+text+'</span>');
            }
            highlight('test');
        </script>        
    </body>
</html>

【讨论】:

  • 你改变了什么?你为什么要改变它?
  • document.body.innerHTML = ... 这太糟糕了,您不应该重写整个body 来只更改其中的一小部分。
猜你喜欢
  • 2012-09-28
  • 2010-11-20
  • 2012-08-14
  • 2014-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多