javascript jQuery 函数之外的变量作用域

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4153855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:31:31  来源:igfitidea点击:

Variable Scope outside jQuery function

javascriptjquery

提问by Atif Mohammed Ameenuddin

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:

我试图在 HTML 中识别 div 元素的高度,但我无法访问该函数之外的值。这是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 $heightas undefined. How can I retain the value of $height?

第一个警报函数有效,但第二个抛出并错误$height为未定义。我怎样才能保留 的价值$height

回答by Nick Craver

You can just remove the varlike this:

你可以var像这样删除:

$height = $tmp_cont.height();

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

如果您想要一个全局变量,请省略var, 或者更明确地:

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);