匹配网页中的字符串和HTML标签

Match a String in a Webpage along with HTML tags

本文关键字:HTML 标签 字符串 网页      更新时间:2023-09-26

与下面的代码,我试图匹配一个网页中的文本,以摆脱网页中的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>"); 

但它似乎不起作用…请看看这个,让我知道问题出在哪里……
这是小提琴我已经尝试了下面的代码代替…

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);
 }

但是这完全是从body中移除html标签…

将最后一行代码更改为以下一行…你正在使用赋值操作符,它与变量不与jquery对象。因此,您需要将替换后的html传递给text方法。

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