简体   繁体   中英

How to implement a jQuery plugin with this feature?

So that it can be show or hide this way:

$(selector).pluginName('show')
$(selector).pluginName('hide')

The problem is how do I know which one to show or hide?

I'm now doing it this way:

$.fn.pluginName = function(opts) {  
    var conf = $.extend({},opts);
    return this.each(function() { 
        if(conf && 'conf' == conf.type)
        {
            //ClassName is defined elsewhere
            new ClassName(conf,$(this));
        }
        else
        {
            //**show or hide corresponding instance**
        }
    });
}

You can use data to associate your object with the DOM element it belongs to:

$.fn.pluginName = function(opts) {
  if(typeof(opts) == "string"){
    this.each(function(){
      // Get the associated obj
      var obj = $(this).data('ClassName');
      if(obj){
        if(opts == "show") obj.myShowMethod();
        else if (opts == "hide") obj.myHideMethod();
      }
    })
  } else {
    var conf = $.extend({},opts);  
    this.each(function() { 
      var obj = new ClassName(conf,$(this));
      // Associate your object with this DOM element
      $(this).data('ClassName', obj);
    });
  }
  return this; // Don't break the chain
}

Also check out, Starter for jQuery , which uses the data pattern to associate the object with the DOM element.

.toggle() is probably what you are looking for. It will toggle the element between hidden and shown (depending on what state it is in at the moment).

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