最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Variable Scope outside jQuery function - Stack Overflow

programmeradmin1浏览0评论

I am trying to identify the height of a div element in HTML, but I am 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?

I am trying to identify the height of a div element in HTML, but I am 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?

Share Improve this question edited Dec 24, 2015 at 14:17 Andrew Kozak 1,6602 gold badges22 silver badges35 bronze badges asked Nov 11, 2010 at 11:21 AtifAtif 10.9k21 gold badges67 silver badges97 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 18

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)

  1. 暂无评论