簡體   English   中英

將HTML添加到通過node.nodeValue提取的文本節點

[英]add HTML to text node extracted via node.nodeValue

我想知道在提取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>');
    }
});

OUTPUT:

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()來設置值,因為使用此代碼片段的原始應用程序具有復雜的結構(即它上面的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>'));
    }
});

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

您的問題是您將HTML插入文本節點(因此它被視為文本)。 您不想使用<a href="http://google.com">Google</a>替換_link_ ,而是取出文本節點,從_link_開始刪除文本,附加一個HTML節點(包含錨點)並將_link_之后的所有文本_link_的新文本節點中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM