【问题标题】:Bold text in body using javascript使用javascript在正文中加粗文本
【发布时间】:2013-01-05 16:15:18
【问题描述】:

此代码试图突出显示(通过添加“粗体”标签)HTML 正文中的某些字符。 (这些在JS函数中指定) 但不是文本变为粗体,而是在呈现的 html 页面中得到了“粗体”标签。

虽然我想要一些类似的东西

这是一个测试消息

我明白了

This is a test <b>message</>

任何帮助都会很棒。

    <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title>

<script>

function myFunction(){
        var children = document.body.childNodes;
    for(var len = children.length, child=0; child<len; child++){
     if (children[child].nodeType === 3){ // textnode
        var highLight = new Array('abcd', 'edge', 'rss feeds');
        var contents = children[child].nodeValue;
        var output = contents;
        for(var i =0;i<highLight.length;i++){
            output = delimiter(output, highLight[i]); 
        }


    children[child].nodeValue= output; 
    }
    }
}

function delimiter(input, value) {
    return unescape(input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3'));
}
</script>



</head>
<body>
<img src="http://some.web.site/image.jpg" title="abcd"/>

These words are highlighted: knorex, edge, rss feeds while these words are not: knewedge, abcdef, rss feedssss

<input type ="button" value="Button" onclick = "myFunction()">
</body>
</html>

【问题讨论】:

标签: javascript html highlight


【解决方案1】:

问题是您将 HTML 放入文本节点,因此它被严格地作为文本进行评估。一个简单的解决方法是简单地对 body 元素的 innerHTML 进行操作,如下所示:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title>

<script>

function myFunction(){
  var highLight = ['abcd', 'edge', 'rss feeds'],
      contents = document.body.innerHTML;

  for( i = 0; i < highLight.length; i++ ){
    contents = delimiter(contents, highLight[i]); 
  }

  document.body.innerHTML = contents;
}

function delimiter(input, value) {
  return input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3');
}
</script>



</head>
<body>
<img src="http://some.web.site/image.jpg" title="abcd"/>

These words are highlighted: knorex, edge, rss feeds while these words are not: knewedge, abcdef, rss feedssss

<input type ="button" value="Button" onclick = "myFunction()">
</body>
</html>

【讨论】:

    【解决方案2】:

    一个 textNode 不能有子元素,所以它需要被替换,一种方式;

    替换

    children[child].nodeValue = output;
    

    var n = document.createElement("span");
    n.innerHTML = output;
    children[child].parentNode.replaceChild(n, children[child]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-15
      • 2020-04-27
      • 2016-06-07
      • 2014-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多