我想知道在提取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>
Run Code Online (Sandbox Code Playgroud)
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>');
}
});
Run Code Online (Sandbox Code Playgroud)
OUTPUT:
Hi, this is a Textnode <a href="http://google.com">Google</a>
this is Textnode number 2
element node
Run Code Online (Sandbox Code Playgroud)
我需要的:
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
Run Code Online (Sandbox Code Playgroud)
PS:
我故意不使用html()获取内容,执行a .replace,然后html()再次使用来设置值,因为使用此代码段的原始应用程序具有复杂的结构(即它将运行的DOM元素,以及要生成的字符串)匹配和替换,有超过30个表达式需要搜索和替换,都是特殊字符,如笑脸代码).
但是,只有DOM中的文本节点具有要替换的字符串,并且保留外部html结构和元素是必要的.
上面的代码有效,它只是不在HTML中.有没有办法实现这个目标?
如果我正确理解你,我相信这样做:
$('#msg').contents().each(function() {
if(this.nodeType == 3) {
var u = this.nodeValue;
var reg = /_link_/g;
$(this).replaceWith(u.replace(reg,'<a href="http://google.com">Google</a>'));
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1910 次 |
| 最近记录: |