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

标签 javascript jquery regex

我如何编写一个 javascript/jquery 函数来替换 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>

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

最佳答案

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

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 上的文本节点没有 textContent属性,在 IE 中你应该使用 nodeValue属性,它也没有实现 Node界面。

检查示例 here .

关于javascript - 如何在不影响标记的情况下替换 html 文档中的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1512876/

相关文章:

javascript - 当用户点击 table tbody tr 时

jquery - 获取下一个元素,该元素不一定是同级且没有类

描述二进制数的正则表达式

regex - 正则表达式中的替代捕获组?

javascript - 更改段落选择样式

javascript - 在 React/Redux reducer 中,如何以不可变的方式更新嵌套数组中的字符串?

javascript - 用 css 居中 html 内容

javascript - 为什么我的按钮对 php 和 javascript 不起作用,而我的其他按钮却起作用?

jQuery Change() 不触发原型(prototype)事件处理程序

javascript - JS正则表达式混淆