2012-10-12 64 views
4

在我的web瀏覽器userscript項目中,我需要替換一個文本節點,而不會影響與文本相同的父節點下的其他HTML元素。我需要一個以上的節點來替代它:「jQuery方式」用HTML和文本混合替換文本節點?

<div id="target"> foo/bar; baz<img src="/image.png"></div> 

需求,成爲:

<div id="target"> <a href="#">foo</a>/<a href="#">bar</a>; <a href="#">baz</a><img src="/image.png"></div> 

我知道的jQuery沒有一大堆的文本節點的支持。我知道我可以使用直接DOM調用而不是jQuery。而且我知道我可以做點像$('#target').html(我的新東西+我不想改變的東西)。另外請注意,我想保留最初的空間,這本身似乎很棘手。

我想問這裏的專家是有沒有一種最習慣的jQuery方法來做到這一點?

+0

你怎麼會知道在哪裏,打破了替換文本? –

+0

http://api.jquery.com/contents/ – undefined

+0

@j_mcnally:假設我們有「某種方式」來生成替換文本/ HTML。在我的實際項目中,我將原始文本解析爲一些對象,然後我使用這些對象生成基本相同的文本,但某些單詞更改爲鏈接。 – hippietrail

回答

9

你基本上想用第一個孩子(文本節點)替換新的內容。您需要http://api.jquery.com/replaceWith/

// Text node we want to process and remove 
var textNode = $("#target").contents().first(); 
// Break the text node up 
var parts = textNode.text().split(/\s/); 
// Put links around them 
var replaceWith = ""; 
for (var i =0; i < parts.length;i++) { 
    replaceWith += "<a href='http://www.google.com'>" + parts[i] + "</a> "; 
} 
// Replace the text node with the HTML we created 
textNode.replaceWith(replaceWith); 

http://jsfiddle.net/NGYTB/1/

+0

那麼新的HTML不是純粹基於空格與非空格,而是這種方法絕對是非常好的! – hippietrail

+0

@hippietrail我怎麼知道你將如何分手?這只是一個簡單明瞭的例子,您可以根據自己的需求進行修改。相關部分有權訪問文本節點,並用您將要提供的HTML代替 –

+1

對不起,這不應該是一個投訴,只是一個評論給任何人閱讀。我會接受你的答案,除非真正令人驚訝的事情出現,所以不要擔心( - : – hippietrail

0

嘗試this..edited版本

$('#target').html('<a href="#">mixed</a> text <a href="#">and</a> HTML' + $('#target').html()); 
+0

但是,這將導致'一些文字mixed文本and HTML' – hippietrail

+0

嘗試新一...測試它已經 – soonji

+0

它的工作原理?... – soonji

1

試試這個辦法

// nodeType = 1 corresponds to element node 
    // You are filtering everything out other than that and 
    // removing the textnodes from it.. 
    // contents() will get everything including the text 
    ​$('#target'​).contents().filter(function() { 
     return this.nodeType != 1; 
    }).remove(); 

    // Then you are prepending the div with the html that needs to 
    // replaced with the text... 
    $('#target').prepend('<a href="#">mixed</a> text <a href="#">and</a> HTML'); 
    // This makes sure you do not touch the initial img element inside the div 

您可以添加其他節點類型,如果你不想刪除特定nodetypes CHECK FIDDLE​

+0

這工作。我想這不是一個很普遍的方法,但它似乎是一個問題領域稍微超出jQuery的範圍,這*是*慣用的jQuery。 – hippietrail