【发布时间】:2011-12-03 15:54:00
【问题描述】:
我想知道在提取 contents() 并在其中的所有文本节点上执行替换后,是否有任何方法可以输出 HTML。
jsFiddle:http://jsfiddle.net/bikerabhinav/t8835/1/
HTML:
<div id="msg">
Hi, this is a Textnode _link_<br>
this is Textnode number 2
<br /><a href="http://google.com">element node</a>
</div>
JS:
$('#msg').contents().each(function() {
if(this.nodeType == 3) {
var u = this.nodeValue;
var reg = /_link_/g;
this.nodeValue = u.replace(reg,'<a href="http://google.com">Google</a>');
}
});
输出:
Hi, this is a Textnode <a href="http://google.com">Google</a>
this is Textnode number 2
element node
我需要什么:
Hi, this is a Textnode <a href="http://google.com">Google</a><br> <!-- as a HTML link -->
this is Textnode number 2 <br>
element node
PS:
-
我故意不使用
html()来获取内容,执行.replace,然后再次使用html()设置值,因为使用此sn-p 的原始应用程序具有复杂的结构(即两者它将运行的DOM元素,加上要匹配和替换的字符串,有30多个表达式需要搜索和替换,都是特殊字符,如笑脸代码)。然而,只有 DOM 中的 text-nodes 具有要替换的字符串,并且保持外部 html 结构和元素是必要的。
上面的代码有效,只是不是在 HTML 中。有没有办法做到这一点?
【问题讨论】:
标签: javascript jquery