如何在不影响标记的情况下替换html文档中的文本? [英] How to replace text in html document without affecting the markup?

查看:339
本文介绍了如何在不影响标记的情况下替换html文档中的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写一个javascript / jquery函数来替换html文档中的文本而不影响标记,只影响文本内容?

How can I write a javascript/jquery function that replaces text in the html document without affecting the markup, only the text content?

例如,如果我想要在这里用no style替换style这个词:

For instance if I want to replace the word "style" with "no style" here:

<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>

我不希望替换影响标记,只是文本内容可见用户。

I don't want the replacement to affect the markup, just the text content that is visible to the user.

推荐答案

您必须在文档中查找文本节点,我使用这样的递归函数:

You will have to look for the text nodes on your document, I use a recursive function like this:

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++; 
  } 
}

如果你这样做,你的标记和事件处理程序将保持不变。

If you do it in that way, your markup and event handlers will remain intact.

编辑:更改代码以支持IE,因为IE上的文本节点没有 textContent 属性,在IE中你应该使用 nodeValue 属性,它也没有实现节点界面。

Changed code to support IE, since the textnodes on IE don't have a textContent property, in IE you should use the nodeValue property and it also doesn't implements the Node interface.

检查示例这里

这篇关于如何在不影响标记的情况下替换html文档中的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆