我想实现类似功能://前端调用
$(function(){
  $("#id").YSZ({   //初始化
     par1:"张三",
     par2:"男"
  });
  $("#id2").click(function(){
     $("#id").YSZ("TEST","测试");  //调用方法,第一个参数为方法名,第二个为参数
  });
})我的意思是:当传入对象的时候,插件执行初化,当传入两个字符串参数时,就是调用插件内置的方法!请问该如何实现??

解决方案 »

  1.   

    我之前是这样写的:(function($){
       $.fn.YSZ=function(options){
           var defaults={
             par1:"姓名",
             par2:"性别" 
           };
           $.extend(defaults,options);
           this._init=function(){
               $(this).html(opt.par1+"@"+opt.par2);
           }
           this.TEST=function(str){
               alert(str);
           }
           this._init();
           return this;
       }
    })(jQuery)但这样写显然不行,望大师指点一二!
      

  2.   

    我觉得,你想要的应该是这个
    见代码
    <input class="a" style="width:500px">
    <input class="a" style="width:500px">
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script>
    $.fn.YSZ = function(p1,p2){
    if(typeof(p1)=="string")
    $.fn.YSZ.methods[p1](this, p2);
    else
    //做些初始化的事情
    this.height(p1.height);
    }
    $.fn.YSZ.methods = {
    fun1:function(jqueryObj, p){
    jqueryObj.get(0).value = "fun1 called param:"+p.p1+","+p.p2;
    },
    fun2:function(jqueryObj, p){
    jqueryObj.get(1).value = "fun2 called param:"+p.p1+","+p.p2+","+p.p3;
    }
    }$(".a").YSZ("fun1",{p1:"参数1",p2:"参数2"});
    $(".a").YSZ("fun2",{p1:"参数3",p2:"参数4",p3:"参数5"});
    $(".a").YSZ({height:100});
    </script>
      

  3.   

    仔细看高亮部分哦
    $(".a").YSZ("fun1",{p1:"参数1",p2:"参数2"});
    $(".a").YSZ("fun2",{p1:"参数3",p2:"参数4",p3:"参数5"});
      

  4.   

    非常感谢,我后来是这样实现的(function($){    
       $.fn.YSZ=function(options){  
          if(typeof options==="string")
          { $.fn.YSZ[options](argments[1]);return}      
          var defaults={          
            par1:"姓名",          
            par2:"性别"        
         };        
        $.extend(defaults,options);        
        this._init=function(){            
           $(this).html(opt.par1+"@"+opt.par2);        
         }        
        this.TEST=function(str){            
               alert(str);        
        }        
       this._init(); 
       $.fn.YSZ.TEST=this.test;       
       return this;    

    })(jQuery) 这样就可以啦!