【问题标题】:add HTML to text node extracted via node.nodeValue将 HTML 添加到通过 node.nodeValue 提取的文本节点
【发布时间】: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


    【解决方案1】:

    您的问题是您将 HTML 插入到文本节点中(因此它被视为文本)。您不想用&lt;a href="http://google.com"&gt;Google&lt;/a&gt; 替换_link_,而是要获取文本节点,从_link_ 开始删除文本,附加一个HTML 节点(包含锚点)并将_link_ 之后的所有文本放入之后是一个新的文本节点。

    【讨论】:

      【解决方案2】:

      如果我对您的理解正确,我相信会这样做:

      $('#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>'));
          }
      });
      

      http://jsfiddle.net/t8835/2/

      【讨论】:

      • 太棒了!正是需要的。谢谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多