Mootools过滤插件

时间:2011-12-22 12:27:40

标签: javascript filter mootools selector

你可以帮助我:

请查看此演示:Plugin demo 插件说明:Plugin description

如何在列表顶部仅显示匹配的项目,并在输入输入时隐藏不匹配? 谢谢!

1 个答案:

答案 0 :(得分:1)

当然,你可以使用onShow和onHide处理程序来完成它。 见这里:http://jsfiddle.net/ypfPY/3/

var myFilter = new ElementFilter('search-term', '#my-list li', {
    trigger: 'keyup',
    cache: false,
    onShow: function(element) {
       element.setStyle('display', 'block');
    },
    onHide: function(element) {
       element.setStyle('display', 'none');
    }
});

坦率地说,我在ElementFilter源代码中遇到了一系列错误(在显示所有项目时首先检索“显示”和false而不是true,因为matchOverride是错误的),所以,最好从这里获取源代码:

var ElementFilter = new Class({

  // implements
  Implements: [Options,Events],

  // options
  options: {
    cache: true,
    caseSensitive: false,
    ignoreKeys: [13, 27, 32, 37, 38, 39, 40],
    matchAnywhere: true,
    property: 'text',
    trigger: 'mouseup',
    onStart: $empty,
    onShow: $empty,
    onHide: $empty,
    onComplete: $empty
  },

  //initialization
  initialize: function(observeElement,elements,options) {
    //set options
    this.setOptions(options);
    //set elements and element
    this.observeElement = document.id(observeElement);
    this.elements = $$(elements);
    this.matches = this.elements;
    this.misses = [];
    //start the listener
    this.listen();
  },

  //adds a listener to the element (if there's a value and if the event code shouldn't be ignored)
  listen: function() {
    //add the requested event
    this.observeElement.addEvent(this.options.trigger,function(e) {
    //if there's a value in the box...
    if(this.observeElement.value.length) {
      //if the key should not be ignored...
      if(!this.options.ignoreKeys.contains(e.code)) {
        this.fireEvent('start');
        this.findMatches(this.options.cache ? this.matches : this.elements);
        this.fireEvent('complete');
      }
    }
    else{
      //show all of the elements - changed to true
      this.findMatches(this.elements,true);
    }
  }.bind(this));
},

//check for matches within specified elements
findMatches: function(elements,matchOverride) {
  //settings
  var value = this.observeElement.value;
  var regExpPattern = this.options.matchAnywhere ? value : '^' + value;
  var regExpAttrs = this.options.caseSensitive ? '' : 'i';
  var filter = new RegExp(regExpPattern, regExpAttrs);
  var matches = [];                
  //recurse
  elements.each(function(el){
    var match = matchOverride == undefined ? filter.test(el.get(this.options.property)) : matchOverride;
   //if this element matches, store it...
   if(match) { 
     // default value added  
     if(!el.retrieve('showing', true)){
       this.fireEvent('show',[el]);
     }
     matches.push(el); 
     el.store('showing',true);
   }
   else {
     if(el.retrieve('showing', true)) {
       this.fireEvent('hide',[el]);
     }
     el.store('showing', false);
   }
   return true;
 }.bind(this));
 return matches;
 }
});