通过搜索查找文本并高亮显示错误

Find text by search and highlight gets error

本文关键字:高亮 显示 错误 文本 搜索 查找      更新时间:2023-09-26

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

:

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

更新小提琴:https://jsfiddle.net/gaezs6s8/

text()

获取匹配元素集合中每个元素(包括其后代元素)的组合文本内容,或者设置匹配元素的文本内容。

html()

获取匹配元素集合中第一个元素的HTML内容,或者设置每个匹配元素的HTML内容。