2009-10-03 34 views
4

我該如何寫一個javascript/jquery函數來替換html文檔中的文本而不影響標記,只有文本內容?如何在不影響標記的情況下替換html文檔中的文本?

舉例來說,如果我想用「無風」在這裏一詞取代「風格」:

<tr> 
<td style="width:300px">This TD has style</td> 
<td style="width:300px">This TD has <span class="style100">style</span> too</td> 
</tr> 

我不想更換影響的標記,只是文本內容是可見的用戶。

回答

13

你將不得不尋找在文檔中的文本節點,我使用遞歸函數如下:

function replaceText(oldText, newText, node){ 
    node = node || document.body; // base node 

    var childs = node.childNodes, i = 0; 

    while(node = childs[i]){ 
    if (node.nodeType == 3){ // text node found, do the replacement 
     if (node.textContent) { 
     node.textContent = node.textContent.replace(oldText, newText); 
     } else { // support to IE 
     node.nodeValue = node.nodeValue.replace(oldText, newText); 
     } 
    } else { // not a text mode, look forward 
     replaceText(oldText, newText, node); 
    } 
    i++; 
    } 
} 

如果以這種方式做到這一點,您的標記和事件處理程序將保持不變。

編輯:更改代碼來支持IE,因爲IE瀏覽器的textnodes沒有textContent屬性,在IE瀏覽器,你應該使用nodeValue財產,它也不會實現了Node接口。

檢查示例here

+0

非常感謝@CMS,您幫我解決了這個問題:http://stackoverflow.com/questions/1512053/how-to-force-breaking-of-non-breakable-strings/ – Sylvain 2009-10-03 07:02:10

+1

'node.data'應該適用於所有瀏覽器。 – James 2009-10-03 14:38:50

+0

一段很棒的代碼,我們可以讓它更快嗎? – crosenblum 2010-01-27 21:05:40

4

使用:contains選擇器查找具有匹配文本的元素,然後替換其文本。

$(":contains(style)").each(function() { 
    for (node in this.childNodes) { 
    if (node.nodeType == 3) { // text node 
     node.textContent = node.textContent.replace("style", "no style"); 
    } 
    } 
}); 

不幸的是,因爲它從所有子節點,而不僅僅是子節點並如期更換將無法正常工作剔除HTML你不能使用text()這一點。

+1

不要使用「for ... in」來遍歷類似數組的對象..傳統的for/while循環要快得多。 – James 2009-10-03 14:40:10

相關問題