gpt4 book ai didi

javascript - 将网页中的字符串与 HTML 标记匹配

转载 作者:行者123 更新时间:2023-11-30 18:35:49 25 4
gpt4 key购买 nike

使用下面的代码,我试图匹配网页中的文本以去除页面中的 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是 fiddle 我试过下面的代码..

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 标签...

最佳答案

将代码的最后一行更改为下面一行...您正在使用赋值运算符,它与变量一起工作,而不是与 jquery 对象一起工作 ..因此您需要将替换的 html 传递给 text 方法。

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

关于javascript - 将网页中的字符串与 HTML 标记匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8253110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com