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

标签 javascript jquery html google-chrome-extension

我进行了两次不同的尝试,在 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 树上 bodydiv 的 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/

相关文章:

javascript - 使用 Enter Keydown Event 移动到下一个输入

javascript - 自定义谷歌地图按钮位置

javascript - 如何在 Django 中实现这个 - 后退按钮 - 保留请求中的数据

javascript - 带有事件点的 jQuery 轮播

javascript - html Canvas 上的雨滴动画

javascript - ES中export和modules.export有什么区别

jquery - 专门为选择元素分配 Jquery-UI 的 css?

css - 重叠式选单无法在Safari上运作?

javascript - 在选定的输入字段下方显示一个 div?没有 JQuery

html - 将 margin-top 设置为 h1 后,如何删除 div 上方的空白区域?