我进行了两次不同的尝试,在 Chrome 扩展程序中使用 JQuery 替换网页中出现的单个单词的所有位置。这两种尝试都有点有效,但都没有作为替换网页中出现的所有单词的通用方法。
如何编写一个脚本来替换网页中某个单词的所有出现?
继续阅读两次不同尝试的详细信息,这两次尝试都都奏效,但由于不同的原因而失败。
尝试 1:替换没有子节点的文本。如果使用子节点进行格式化,则此操作会失败。例如,解析以下内容时会失败:
<p>StringToReplace <strong>doesn't</strong> get replaced!</p>
我用于此尝试的确切代码是:
$("*").each(function () {
if ($(this).children().length == 0) {
$(this).text(replaceStrings($(this).text()));
}
}
(replaceStrings 是一个单独的函数,具有一堆任意调用来替换)
尝试 2:替换可能仅包含文本的节点的 HTML(例如 p
)。这会失败,因为我的脚本需要处理的某些网页的文本出现在正文等标签内。如果我尝试替换正文的 HTML,则会产生破坏某些页面功能的不良副作用。在我看来,尝试通过替换 DOM 树上 body
或 div
的 HTML 来处理网站功能受损的每种边缘情况将是一场噩梦。
我第二次尝试使用的代码:
$("*").each(function () {
if (
$(this)[0].nodeName.toLowerCase() == "font"
|| $(this)[0].nodeName.toLowerCase() == "span"
|| $(this)[0].nodeName.toLowerCase() == "p"
//|| $(this)[0].nodeName.toLowerCase() == "body"
// || $(this)[0].nodeName.toLowerCase() == "div"
){
$(this).html(replaceStrings($(this).html()));
}
}
如何编写一个脚本来替换网页中某个单词的所有出现?
谢谢!
最佳答案
我不喜欢第一个答案中的插件,因为它只能工作一层深度。这是一个遍历所选元素下的整个结构的版本。
用法:$(".content").replaceText("visitor","John Doe");
// Replace occurences of 'search' with 'replace' anywhere in the element.
// New HTML tags will be rendered, except if 'text_only' is true.
$.fn.replaceText = function(search, replace, text_only) {
return this.each(function(){
var v1, v2, rem = [];
$(this).find("*").andSelf().contents().each(function(){
if(this.nodeType === 3) {
v1 = this.nodeValue;
v2 = v1.replace(search, replace);
if(v1!=v2) {
if(!text_only && /<.*>/.test(v2)) {
$(this).before( v2 );
rem.push(this);
}
else this.nodeValue = v2;
}
}
});
if(rem.length) $(rem).remove();
});
};
关于javascript - 如何使用JQuery替换网页中所有出现的某个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5153909/