Javascript 如何在不影响标记的情况下替换html文档中的文本?
如何编写一个javascript/jquery函数来替换html文档中的文本而不影响标记,只影响文本内容 例如,如果我想在此处将“样式”一词替换为“无样式”:Javascript 如何在不影响标记的情况下替换html文档中的文本?,javascript,jquery,regex,Javascript,Jquery,Regex,如何编写一个javascript/jquery函数来替换html文档中的文本而不影响标记,只影响文本内容 例如,如果我想在此处将“样式”一词替换为“无样式”: 这辆车很有风格 这个TD也很有风格 我不希望替换会影响标记,只想影响用户可见的文本内容。您必须查找文档上的文本节点,我使用如下递归函数: function replaceText(oldText, newText, node){ node = node || document.body; // base node var
这辆车很有风格
这个TD也很有风格
我不希望替换会影响标记,只想影响用户可见的文本内容。您必须查找文档上的文本节点,我使用如下递归函数:
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关闭。后来的版本(2012)似乎还可以。解决方法是在if(node.textContent)
循环的一部分中使用node.nodeValue=…
进行分配,而不考虑使用textContent。为什么不在所有浏览器中使用node.data
?不要使用“for…in”来循环类似数组的对象。。传统的for/while循环要快得多。
$(":contains(style)").each(function() {
for (node in this.childNodes) {
if (node.nodeType == 3) { // text node
node.textContent = node.textContent.replace("style", "no style");
}
}
});