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

标签 javascript jquery html regex

搜索文本时,它会找到并突出显示正确的文本,但其他元素会被清除,例如 <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/

相关文章:

带有可选子字符串的 JavaScript RegEx 模式

html - 使用 Express 在 node.js 中的数组中接收表单数据?

javascript - 如何从客户端扩展 Firebase 身份验证登录 session ?

javascript - 隐藏所有带有ID的元素

javascript - window.onload 和 document.ready : execution order in case specified multiple times

javascript - 即使输入有效,Internet Explorer 也不会更改跨度内容

javascript 未在页面上加载

javascript - 从嵌套在 Javascript 中的 iframe 标签中删除垂直滚动条

php - 如何从 HTML/PHP 中的单个 <select> 变量获取多个值?

javascript - iron-router notFound 模板在 meteor 中不起作用