2011-03-01 61 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(); 
    }); 
}; 
相關問題