我编写了此函数,该函数接受一个单词作为输入,并将其放在<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()
替换值,也会返回相同的结果。编辑
这是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]);