且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在不影响标记的情况下替换html文档中的文本?

更新时间:2022-11-03 11:05:33

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

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.

检查示例这里