2011-11-24 26 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

更新代码..尝试现在希望它会工作这段时间。 –

相关问题