Javascript 如何在不影响标记的情况下替换html文档中的文本?
如何编写一个javascript/jquery函数来替换html文档中的文本而不影响标记,只影响文本内容 例如,如果我想在此处用无样式替换单词样式:Javascript 如何在不影响标记的情况下替换html文档中的文本?,javascript,jquery,regex,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>
<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上的textnodes没有属性,在IE中,您应该使用该属性,它也不实现接口
检查示例。使用选择器查找具有匹配文本的元素,然后替换它们的文本
$(":contains(style)").each(function() {
for (node in this.childNodes) {
if (node.nodeType == 3) { // text node
node.textContent = node.textContent.replace("style", "no style");
}
}
});
不幸的是,您不能使用它,因为它会从所有子节点(而不仅仅是子节点)中删除HTML,替换将无法按预期工作。非常感谢@CMS,您帮助我解决了这个问题:请注意MSIE9的2011版本-它们支持node.textContent,但是如果您尝试使用node.textContent=分配一个新值。。。然后,这些版本使整个浏览器崩溃,该网站出现问题,导致Internet Explorer关闭。以后的版本看起来还可以。解决方法是使用node.nodeValue=。。。在循环的if node.textContent部分中,不管如何,只要忘记使用textContent即可。为什么不在所有浏览器中使用node.data?不要使用for…in来循环类似数组的对象。。传统的for/while循环要快得多。