使用javascript在正文中显示粗体文本
此代码试图突出显示(通过添加“bold”标记)HTML正文中的某些字符。(这些在JS函数中指定) 但是文本没有变为粗体,而是在呈现的html页面中得到了“bold”标记作为结果 而我想要的是 这是一条测试消息 我明白了使用javascript在正文中显示粗体文本,javascript,html,highlight,Javascript,Html,Highlight,此代码试图突出显示(通过添加“bold”标记)HTML正文中的某些字符。(这些在JS函数中指定) 但是文本没有变为粗体,而是在呈现的html页面中得到了“bold”标记作为结果 而我想要的是 这是一条测试消息 我明白了 这是一条测试消息 任何帮助都会很棒 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>Test&
这是一条测试消息
任何帮助都会很棒
<!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>
试验
函数myFunction(){
var children=document.body.childNodes;
对于(var len=childrence.length,child=0;child而言,问题在于您将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>
试验
函数myFunction(){
var highLight=['abcd','edge','rss提要'],
contents=document.body.innerHTML;
对于(i=0;i
textNode不能有子元素,因此需要单向替换
替换
children[child].nodeValue = output;
与
类似于rss提要的案例如何?
?可能的重复是昨天海报问题的重复,尽管可能更好地表述。或者更确切地说,是重复的
children[child].nodeValue = output;
var n = document.createElement("span");
n.innerHTML = output;
children[child].parentNode.replaceChild(n, children[child]);