gpt4 book ai didi

javascript - 通过搜索查找文本并突出显示出现错误

转载 作者:行者123 更新时间:2023-12-02 14:11:19 24 4
gpt4 key购买 nike

搜索文本时,它会找到并突出显示正确的文本,但其他元素会被清除,例如 <p> , <ul> , <b> , <strong> 。所有元素都被删除/清理!

HTML:

<div class="ray-search">
<div class="field" id="ray-search-form">
<input type="text" id="searchfor" placeholder="what are you searching for?" />
<button type="button" id="search">Press to Find!</button>
</div>
</div>

<article id="ray-all_text">
<p>
This manual and web site, all information and data and photos contained herein, are the s...
</p>
</article>

JS:

setTimeout(function() {
$('button#search').click(function() {
var page = $('#ray-all_text');
var pageText = page.text().replace("<span>", "").replace("</span>");
var searchedText = $('#searchfor').val();
var theRegEx = new RegExp("(" + searchedText + ")", "igm");
var newHtml = pageText.replace(theRegEx, "<span>$1</span>");

page.html(newHtml);
$('html, body').animate({
scrollTop: $("#ray-all_text span").offset().top
}, 2000);
});
}, 1000);

请检查 JSFiddle 示例:https://jsfiddle.net/8snb3o4h
为什么会发生这种情况?有解决办法吗?

最佳答案

text() 删除所有标记。 html() 将保持其完整。

更改:

var pageText = page.text().replace("<span>", "").replace("</span>");

var pageText = page.html().replace("<span>", "").replace("</span>");
<小时/>

更新的 fiddle :https://jsfiddle.net/gaezs6s8/

文本()

Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.

html()

Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.

关于javascript - 通过搜索查找文本并突出显示出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39536179/

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