开发者

jQuery: Highlighting a live search result

开发者 https://www.devze.com 2022-12-24 14:40 出处:网络
I\'m fairly new to jQuery - I found this snippet on the net and adapted it for my purposes. It searches a page as you type and removes all objects which don\'t contain the value you searched for. It w

I'm fairly new to jQuery - I found this snippet on the net and adapted it for my purposes. It searches a page as you type and removes all objects which don't contain the value you searched for. It works like a charm, however I would like to be able to highlight the string in the results which the user has typed in the input field.

I know I need to use something like addClass.('highlight'), but I have no idea where and how I can do it in this snippet. Can you help me out?


(function($) {
  var Search = function(block) {
    this.callbacks = {};
    block(this);
  }
  Search.prototype.all = function(fn) { this.callbacks.all = fn; }
  Search.prototype.reset = function(fn) { this.callbacks.reset = fn; }
  Search.prototype.empty = function(fn) { this.callbacks.empty = fn; }
  Search.prototype.results = function(fn) { this.callbacks.results = fn; }
  function query(selector) {
    if (val = this.val()) {
      return $(selector + ':Contains("' + val + '")');;
    } else {开发者_JAVA百科
      return false;
    }
  }

  $.fn.search = function search(selector, block) {
    var search = new Search(block);
    var callbacks = search.callbacks;

    function perform() {
      if (result = query.call($(this), selector)) {
        callbacks.all && callbacks.all.call(this, result);
        var method = result.size() > 0 ? 'results' : 'empty';
        return callbacks[method] && callbacks[method].call(this, result);
      } else {
        callbacks.all && callbacks.all.call(this, $(selector));
        return callbacks.reset && callbacks.reset.call(this);
      };
    }

    $(this).live('keypress', perform);
    $(this).live('keydown', perform);
    $(this).live('keyup', perform);
    $(this).bind('blur', perform);
  }
})(jQuery);

(function($) {
    $(document).ready(function() {
        $('input[name="livesearch"]').search('.element', function(on) {
            on.all(function(results) {
                var size = results ? results.size() : 0
                $('#count').text(size + ' results.');
            });

            on.reset(function() {
                $('#none').hide();
                $('#hint').show();
                $('.element').show();
            });

            on.empty(function() {
                $('#none').show();
                $('#count').hide();
                $('.element').hide();
            });

            on.results(function(results) {
                $('#none').hide();
                $('.element').hide();
                results.show();
            });
        });
    });
})(jQuery);


I use this Highlight plugin to do something similar

0

精彩评论

暂无评论...
验证码 换一张
取 消