highlight text in table word by word not whole spa

2020-05-03 12:17发布

I want to create the filter for html table like of website (ctrl + f), but current code is highlighting all the span on searching entering single word without any plugin. Just like the image below

Html Table filtering

$("#search").keyup(function() {
  console.log($(this).val());
  if ($(this).val() == "") {
    $("#search_here").find("tr").not("tr:first").find("span").removeClass('highlighted');
    $("#search_here").find("tr").not("tr:first").find("span").find(".inputType").removeClass('highlighted');
    return false;
  }
  
  var data = this.value.toUpperCase().split(" ");
  
  $("#search_here").find("tr").not("tr:first").find("span").each(function(index, elem) {
    var $elem = $(elem);
    //console.log($elem);
    for (var d = 0; d < data.length; ++d) {
      // Highlight
      if ($elem.text().toUpperCase().indexOf(data[d]) != -1) {
        console.log($elem.text());
        $elem.addClass('highlighted');
      } else {
        $elem.removeClass('highlighted');
      }
      //console.log();
    }
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <span>2019-04-15 10:48:26</span>
    </td>
    <td>
      <span>I19040800</span>
    </td>
    <td>
      <span class="pull-left">District Abbottabad Store</span>
    </td>
    <td>
      <span>Routine</span>
    </td>
    <td>
      <span>1</span>
    </td>
    <td>
      <span>kp_str</span>
    </td>
    <td>
      <span>2019-04-15 10:49:22</span>
    </td>
    <td>
      <span>Dispatched</span>
    </td>
  </tr>
</table>

2条回答
Ridiculous、
2楼-- · 2020-05-03 12:57

Ok so like the comments have mentioned you need to be wrapping the matched text, not adding a class to the parent element.

I've quickly put together a working example which achieves this effect: https://jsfiddle.net/53bnwxcj/

The jQuery doing the heavy lifting...

var $table = $('table#search_here');
var $input = $('input#search');

/**
 * Listen for multiple input events
 */
$input.on('change cut paste keyup keydown', function() {
  // Get and clean the input value
  var value = $input.val().toString().toLowerCase().trim();

  // Get all table rows
  var $rows = $table.find('tr').not(':first');

  // Remove already highlighted text
  $rows.find('.highlighted').contents().unwrap();

  // Check if the input has a value
  if (value) {

    // Split the input by spaces into an array
    var data = value.toLowerCase().split(' ');

    // Loop each span found in rows
    $rows.find('span').each(function() {
      var $el = $(this);
      var content = $el.text();

      // Loop each data part
      for (var d = 0; d < data.length; d++) {
        var query = data[d];
        var length = query.length;
        var position = content.toLowerCase().indexOf(query);

        // If the query is found in the span contents
        if (position !== -1) {

          // Get the begining of the string
          var before = content.slice(0, position);

          // Get the part of the string that matches the query
          var middle = content.slice(position, position + length);

          // Now get the last segment
          var after = content.slice(position + length, content.length);

          // Wrap the middle text in a span.highlighted
          var $highlight = $('<span>', {
            class: 'highlighted',
            text: middle
          });

          // Replace content
          $el.html(before + $highlight.prop('outerHTML') + after);
        }

      }
    })
  }
});

It's worth noting that this code can only handle a single "highlight" per span. So if you had 2 matching queries in a single span only the last would be highlighted.

I've written this to help give you a starting point.

Another option is to use a third-party plugin like this one: http://bartaz.github.io/sandbox.js/jquery.highlight.html

查看更多
▲ chillily
3楼-- · 2020-05-03 13:10

Try something like below:

$("body p").highlight($elem);

This might help you.

Please go through below Plugin Url for reference.

URL: https://www.jqueryscript.net/text/Text-Highlighting-Filtering-Plugin-with-jQuery.html

查看更多
登录 后发表回答