How to access properties of function within function
How do I access isExpanded
, collapsedHeight
and expandedHeight
inside the jQuery click handler for element
.
this
means something else inside the click handler than it does outside of it.
function CoolSelect(element)
{
this.element=element;
this.isExpanded=false;
this.collapsedHeight=$(element).height()开发者_如何学运维;
this.expandedHeight=this.collapsedHeight+$('ul',element).height();
$(this.element).click(function()
{
var newHeight;
if(this.isExpanded){newHeight=this.collapsedHeight;}
else{newHeight=this.expandedHeight;}
$(this.element).animate({height:newHeight},100,'liniar');
});
}
Thank you.
Copy the value of this
to another variable in the outer function.
var that = this;
Then use that
in the inner function.
You need to save a reference to this.
This code uses var that = this;
function CoolSelect(element)
{
this.element=element;
this.isExpanded=false;
this.collapsedHeight=$(element).height();
this.expandedHeight=this.collapsedHeight+$('ul',element).height();
var that = this;
$(this.element).click(function()
{
var newHeight;
if(that.isExpanded){newHeight=that.collapsedHeight;}
else{newHeight=that.expandedHeight;}
$(that.element).animate({height:newHeight},100,'liniar');
});
}
精彩评论