开发者

Variable Scope outside jQuery function

I am trying to identify the height of a div element in HTML, but I am开发者_C百科 not able to access the value outside of the function. This is the jQuery:

jQuery.noConflict();

(function($) { 
    $(function() {
        $tmp_cont = $('<div></div>');
        $tmp_cont.html($content);
        $tmp_cont.hide();
        $('body').append($tmp_cont);

        var $height = $tmp_cont.height();

        alert ($height);
    });
})(jQuery);

alert ($height);

The first alert function works, but the second throws and error with $height as undefined. How can I retain the value of $height?


You can just remove the var like this:

$height = $tmp_cont.height();

If you want a global variable, leave off the var, or more explicitly:

window.$height = $tmp_cont.height();

Or if you still want it local, just declare it higher up, like this:

jQuery.noConflict();
var $height;
(function($) { 
    $(function() {
        $tmp_cont = $('<div></div>');
        $tmp_cont.html($content);
        $tmp_cont.hide();
        $('body').append($tmp_cont);

        $height = $tmp_cont.height();
        alert ($height);
    });
})(jQuery);
alert ($height);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜