jQuery搜索功能未突出显示文本

时间:2018-08-13 15:52:33

标签: jquery search highlight

我有这个搜索功能,我打算在内容框div内的搜索框中突出显示输入文本的值。唯一的问题是它不起作用。调用该函数时,我得到console.log的“ wording ...”,但没有错误或突出显示。任何反馈将不胜感激,谢谢!

function search() {
//highlight text
  var o = { words: $('#searchInput').val() };
  highlight('#searchtextone', o);

  function highlight(id, options) {
    var o = {
        words: '',
        caseSensitive: false,
        wordsOnly: true,
        template: '$1$2$3',
        class: 'highlight',
        background: 'lightskyblue',
        color: 'black'
      },
      pattern;
    $.extend(true, o, options || {});

    if (o.words.length == 0) {
      console.log('no words');
      return;
    }
    pattern = new RegExp(
      '(>[^<.]*)(' + o.words + ')([^<.]*)',
      o.caseSensitive ? '' : 'ig'
    );

    $(id).each(function() {
      var content = $(this).html();
      if (!content) return;
      $(this).html(content.replace(pattern, o));
      // $("#searchtextone").addClass("highlight");
      console.log('wording...');
    });
  }
}

HTML-输入

<input id="searchInput" onkeyup="search()" class="search-box" type="text" placeholder="Search"><i type="reset" class="fas fa-search"></i></input>

HTML-内容

<p id="searchtextone" class="searchtext searchtextone">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

1 个答案:

答案 0 :(得分:0)

好的,所以我找到了解决此问题的方法。我使用了这个库: https://github.com/yjseo29/highlight.js

我的代码如下

var searchCnt = 0;

var option = {
  color: "black",
  background: "lightskyblue",
  bold: false,
  class: "high",
  ignoreCase: true,
  wholeWord: false
};

var originalContent = $("#searchtextone").html();
searchCnt = $("#searchtextone").highlight($("#searchInput").val(), option);
$("#matcheCnt").text(searchCnt);

$("#searchInput").keyup(function() {
  $("#searchtextone").html(originalContent);
  $("#searchInput").val(this.value);
  if (this.value == "") return;
  searchCnt = $("#searchtextone").highlight(this.value, option);
  $("#matcheCnt").text(searchCnt);
});

我希望这会帮助下一个可能遇到类似问题的人