将HTML添加到通过node.nodeValue提取的文本节点 [英] add HTML to text node extracted via node.nodeValue
问题描述
我想知道在提取 contents()
并在其中的所有文本节点上执行替换后,是否有任何方法可以输出HTML。
I wanted to know if there's any way I could output HTML after extracting contents()
and performing a replace on all of the text-nodes in it.
jsFiddle: http://jsfiddle.net/bikerabhinav/ t8835 / 1 /
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
我需要的是:
What I need:
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()
来设置值,因为使用此代码段的原始应用程序具有复杂的结构(即,它将运行的DOM元素,以及要匹配和替换的字符串,有超过30个表达式需要搜索和替换,所有都是特殊字符,如笑脸代码)。
I'm deliberately NOT using
html()
to get the contents, perform a.replace
, and then usehtml()
again to set the value because the original application which uses this snippet has complex structure (i.e. both the DOM element on which it will run, plus the string to be matched and replaced, there are over 30 expressions which need to be searched for and replaced, all are special character, like smiley codes).
但是,只有DOM中的文本节点具有要替换的字符串,并且必须保留外部html结构和元素。
However, only text-nodes in the DOM has the string which is to be replaced, and keeping the outer html structure and elements is necessary.
以上代码有效,它不是HTML格式。有没有办法实现这个目标?
The above code works, it's just not in HTML. Is there a way to achieve this?
推荐答案
如果我理解正确,我相信这样做:
If I'm understanding you correctly, I believe this will do:
$('#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>'));
}
});
这篇关于将HTML添加到通过node.nodeValue提取的文本节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!