简体   繁体   中英

How to edit CSS of a JavaScript variable in JS?

I have a live search for a website and it's working just fine but I cannot seem to figure out how to highlight the search term in the result. Below is my JS code. I assume I need to edit the data-search-term variable but I am clueless about how to go about it.

I know only HTML/CSS. No JavaScript.

jQuery(document).ready(function($) {

    $('.training-search-list li').each(function() {
        $(this).attr('data-search-term', $(this).text().toLowerCase());
    });

    $('.training-search-box').on('keyup', function() {

        var searchTerm = $(this).val().toLowerCase();

        $('.training-search-list li').each(function() {

            if ($(this).filter('[data-search-term *= ' + searchTerm + ']').length > 0 || searchTerm.length < 1) {
                $(this).show();
            } else {
                $(this).hide();
            }

        });

    });

});

Thanks in advance.

I made it long time ago

    (function($){

  $('#categoryFilter').focus().keyup(function(event){
    var input = $(this);
    var val = input.val();
    if(val == ''){
      $('#filter li').show();
      $('#filter a span').removeClass('highlighted');
      return true;
    }
    var regexp = '\\b(.*)';
    for (var i in val) {
      regexp += '('+val[i]+')(.*)';
    }
    regexp += '\\b';
    $('#filter li').show();
    $('#filter').find('a > span').each(function(){
      var span = $(this);
      var resultats = span.text().match(new RegExp(regexp,'i'));
      if(resultats){
        var string = '';
        for (var i in resultats){
          if(i > 0){
            if(i%2 == 0){
              string += '<span class="highlighted">'+resultats[i]+'</span>';
            }else {
                string += resultats[i];
            }
          }
        }
        span.empty().append(string);
      }else {
        span.parent().parent().hide();
      }
    });
  });
})(jQuery);

Maybe you can try to make your own code with some part of mine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM