2010-01-15 58 views
3

因此,它可以显示或隐藏这样:如何使用此功能实现jQuery插件?

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

的问题是我怎么知道哪一个显示或隐藏?

我现在做这种方式:

$.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** 
     } 
    }); 
} 
+1

如果你正在*做*,我认为你需要'.toggle()'... – 2010-01-15 08:13:51

回答

2

您可以使用data到对象与DOM元素相关联属于:

$.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 
} 

还检查了,Starter for jQuery,它使用data模式对象与DOM元素相关联。

+0

这正是我所追求的!+1 – user198729 2010-01-15 08:23:05

-1

.toggle()可能是你在找什么。它将在隐藏和显示之间切换元素(取决于它现在处于什么状态)。