Highlight text in multiple content divs from input

别来无恙 提交于 2019-12-11 15:16:40

问题


I have this search and highlight function which works fine until I try to search across multiple content divs. What would be the best route to take to get to a solution as I don't want to duplicate the function for each content div.

I was thinking of possibly using a for each function...?

Thank you in advance!

Library:

/**
 * highlight 1.0.0
 * Licensed under MIT
 *
 * Copyright (c) 2016 yjteam
 * http://yjteam.co.kr
 *
 * GitHub Repositories
 * https://github.com/yjseo29/highlight.js
 */

if (typeof jQuery === 'undefined') {
    throw new Error('JavaScript requires jQuery')
}

+function ($) {
    'use strict';
    var version = $.fn.jquery.split(' ')[0].split('.')
    if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1)) {
        throw new Error('JavaScript requires jQuery version 1.9.1 or higher')
    }
}(jQuery);

+function ($) {
    $.fn.highlight = function (word, options) {
        var option = $.extend({
            background: '#ffff00',
            color: '#000',
            bold: false,
            class: '',
            ignoreCase: true,
            wholeWord: true
        }, options);
        var findCnt = 0;

        if(this.length == 0){
            throw new Error('Node was not found')
        }

        var $el = $('<span style="color:'+option.color+';"></span>');
        if(option.bold){
            $el.css('font-weight', 'bold');
        }
        if(option.background != ''){
            $el.css('background', option.background);
        }
        if(option.class != ''){
            $el.addClass(option.class);
        }

        if(option.wholeWord){
            word = '\\b'+escapeRegExp(word)+'\\b';
        }
        var re = new RegExp(word, option.ignoreCase == true ? 'gi':'g');

        this.each(function() {
            var content = $(this).html();

            $(this).html(content.replace(re, function(t){
                findCnt++;
                $el.text(t);
                return $el.get(0).outerHTML;
            }));

        });
        return findCnt;

        function escapeRegExp(string){
            return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
        }
    }
}(jQuery);

Javascript:

//highlight search terms in content
var searchCnt = 0;

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

var textContent = $(".searchtext")
  .html();
// searchCnt = $(".searchtext-One").highlight($("#searchInput").val(), option);
// $("#matcheCnt").text(searchCnt);

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

HTML:

<div class="inner-content">
  <div class="row">
    <div class="col-lg-12 col-md-12 col-sm-12 border-top">
      <h4 class="off-white bold searchtabsheading">Technical Overview </h4>
      <!-- inject overview -->
      <p class="searchtext">first 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>
    </div>
  </div>
  <div class="row">
    <div class="col-lg-12 col-md-12 col-sm-12 border-top">
      <h4 class="off-white bold searchtabsheading">Potential Impact if exploited</h4>
      <!-- inject potential impact(s) -->
      <p class="searchtext">blah blah blah blah</p>
    </div>
  </div>
  <div class="row">
    <div class="col-lg-12 col-md-12 col-sm-12 border-top">
      <h4 class="off-white bold searchtabsheading">Recommendations</h4>
      <!-- inject recommendation(s) -->
      <p class="searchtext">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>
    </div>
  </div>
</div>

回答1:


This is the script I found to work:

// highlight search terms in content
var searchCnt = 0;

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

$("#searchInput").keyup(function() {
  var searchVal = $(this).val();
  if (!searchVal || searchVal === "") {
    return;
  } else {
    $(".searchtext").each(function() {
      $(this).highlight(searchVal, option);
    });
  }
});


来源:https://stackoverflow.com/questions/51836522/highlight-text-in-multiple-content-divs-from-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!