(function(){
var W=window.W=window.$=function(selector){
return new W.core.init(selector);
};

W.core=W.prototype={
/*selector*/
init:function(els){
var elements=[];
for(var i=0,l=els.length;i<l;i++){
var element=arguments[i];
if(typeof element=='string'){
element=document.getElementById(element);
}
}
if(arguments.length===1){
return element;
}
elements.push(element);
return elements;
},
each:function(fn){
for(var i=0,l=this.elements.length;i<l;i++){
fn.call(this,this.elements[i]);
}
return this;
},
setStyle:function(prop,val){
this.each(function(el){
el.style[prop]=val;
});
return this;
},
show:function(){
var that=this;
this.each(function(){
that.setStyle("display","");
});
return this;
},
hide:function(){
var that=this;
this.each(function(){
that.setStyle("display","none");
});
return this;
}
}
W.core.init.prototype=W.core;
})();
然后调用此js
<script type="text/javascript">
window.onload=function(){
$('p').hide();
}
</script>为何链式调用不起作用?

解决方案 »

  1.   

    jquery不是“形”像就可以了,你看看你hide里this指向哪里?
      

  2.   

    this指向哪里?
     回复内容太短了! 
      

  3.   


            // 让init返回当前实例
            init:function(els){
                this.elements=[];
                for(var i=0,l=els.length;i<l;i++){
                    var element=arguments[i];
                    if(typeof element=='string'){
                        element=document.getElementById(element);
                    }
                }        
                this.elements.push(element);
                return this;
            },