gpt4 book ai didi

javascript - 如何使用 JQuery 替换网页中某个单词的所有出现?

转载 作者:行者123 更新时间:2023-11-27 22:49:15 29 4
gpt4 key购买 nike

我进行了两次不同的尝试,以在 Chrome 扩展程序中使用 JQuery 替换网页中所有出现的单个单词。两种尝试都有点有效,但都不是通用方法来替换网页中出现的所有单词。

我如何编写一个脚本来替换网页中所有出现的特定单词?

继续阅读以了解 2 种不同尝试的详细信息,这两种尝试都有点有效但由于不同原因而失败。

尝试 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)。这失败了,因为我的脚本需要处理的某些网页的文本显示在正文之类的标签内。如果我尝试替换 body 的 HTML,它会产生破坏某些页面功能的不良副作用。 IMO 试图通过替换 bodydiv 的 DOM 树上层的 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()));
}
}

我如何编写一个脚本来替换网页中所有出现的特定单词?

谢谢!

最佳答案

我不喜欢第一个答案中的插件,因为它只能在 1 级深度工作。这是遍历所选元素下的整个结构的版本。

用法:$(".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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com