3

このコードは、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>
4

2 に答える 2

2

The problem is that you are putting HTML in to a text node, so it is being evaluated strictly as text. One easy fix would be to simply operate on the innerHTML of the body element, like this:

<!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>
于 2013-01-22T12:43:23.327 に答える
1

textNode は子要素を持つことができないため、一方向に置き換える必要があります。

交換

children[child].nodeValue = output;

var n = document.createElement("span");
n.innerHTML = output;
children[child].parentNode.replaceChild(n, children[child]);
于 2013-01-22T12:45:24.890 に答える