【发布时间】:2016-09-16 16:26:08
【问题描述】:
在搜索文本时,它会找到并突出显示正确的文本,但会清除其他元素,例如 <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
为什么会这样?有解决办法吗?
【问题讨论】:
标签: javascript jquery html regex