繁体   English   中英

使HTML文本加粗

[英]Make HTML text bold

我编写了此函数,该函数接受一个单词作为输入并将其放在<b>标记中,以便在HTML中呈现时将变为粗体。 但是当它确实被渲染时,该单词不是粗体,而是仅带有<b>标记。

这是函数:

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

在提供值和输入时,例如“消息”和“这是测试消息”:

输出为: This is a test <b>message</b>
所需的输出是: This is a test message

即使用value.bold()替换值, value.bold()返回相同的结果。

编辑这是HTML和我正在处理的JS:

                <!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="knorex"/>

            These words are highlighted: abcd, edge, rss feeds while these words are not: knewedge, abcdefgh, rss feedssss

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

我基本上是得到定界符函数的结果并更改子节点的nodeValue

我取回函数所返回的内容的方式是否有问题?

这是我的工作:

children[child].nodeValue = output;

您需要将标记处理为HTML,而不是仅仅设置为替换文本节点中的现有内容。 为此,替换语句

children[child].nodeValue= output; 

通过以下方式:

var newNode = document.createElement('span');
newNode.innerHTML = output;
document.body.replaceChild(newNode, children[child]); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM