2009-10-03 72 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

相关问题