2011-11-24 65 views
1

使用下面的代碼,我試圖匹配網頁中的文本以擺脫頁面中的html標籤。匹配網頁中的字符串以及HTML標籤

var body = $(body); 
    var str = "Search me in a Web page"; 
    body.find('*').filter(function() 
    { 
    $(this).text().indexOf(str) > -1; 
    }).addClass('FoundIn'); 
    $('.FoundIn').text() = $('.FoundIn').text().replace(str,"<span class='redT'>"+str+"</span>"); 

但它似乎並不工作..請看看這個,讓我知道問題出在哪裏?
here是我曾嘗試下面的代碼,而不是..

小提琴
function searchText() 
{ 
    var rep = body.text(); 
    alert(rep); 
    var temp = "<font style='color:blue; background-color:yellow;'>"; 
    temp = temp + str; 
    temp = temp + "</font>"; 
    var rep1 = rep.replace(str,temp); 
    body.html(rep1); 
} 

但是,這完全去除身體的HTML標籤......你的代碼

回答

1

改變最後一行下面一個...... 您使用賦值運算符,其工作與變量不與jQuery對象 ..所以你需要通過替換的HTML文本方法。

$('.FoundIn').text($('.FoundIn').text().replace(str,"<span class='redT'>"+str+"</span>")) 
+0

不過它不匹配字符串.. – Exception

1
try this. 
$('*:contains("Search me in a Web page")').text("<span class='redT'>Search me in a Web page</span>"); 
+0

更新代碼..嘗試現在希望它會工作這段時間。 –