开发者

How to access properties of function within function

开发者 https://www.devze.com 2023-03-21 13:29 出处:网络
How do I access isExpanded, collapsedHeight and expandedHeight inside the jQuery click handler for element.The way it\'s written now won\'t work because this means something else inside the click hand

How do I access isExpanded, collapsedHeight and expandedHeight inside the jQuery click handler for element.

The way it's written now won't work because 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');
    });
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号