2011-03-01 24 views
2

我做了两次不同的尝试,在Chrome扩展中使用JQuery替换网页中所有单词的出现。两种尝试种类的都起作用,但都不能用作通用方法,以便从网页中替换所有出现的单词。如何使用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)。这会失败,因为我的脚本需要处理的一些网页的文本正好出现在身体等标签内。如果我尝试替换body的HTML,它会在某些页面上打破功能的不良副作用。国际海事组织(IMO)试图通过替代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())); 
    } 
} 

我怎么可以编写脚本,用于替换某个单词出现的所有网页?

谢谢!

+2

顺便说一句,你的第二次尝试的选择很容易被写作'$( '字型,跨度,P')'否定需要检查'nodeName'。 – roryf 2011-03-01 11:35:20

回答

0

我还没有彻底测试这一点,但它应该指向你在正确的方向:

$('*', 'body') 
    .andSelf() 
    .contents() 
    .filter(function() { 
     return this.nodeType === 3; 
    }) 
    .each(function() { 
     this.nodeValue = replaceStrings(this.nodeValue); 
    }); 

(基于this answerthis plugin帮助一起)

+0

感谢roryf,但我已经实现了hubbl的解决方案,它的工作完美,所以我可能不会测试这一个。 – Trindaz 2011-03-01 11:57:23

3

我不喜欢的插件在第一个答案中,因为它只能工作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(); 
    }); 
}; 
相关问题