簡體   English   中英

變量范圍在jQuery函數之外

[英]Variable Scope outside jQuery function

我試圖在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);

第一個警報功能工作,但第二個拋出和錯誤與$height未定義。 我怎樣才能保留$height的值?

您可以像這樣刪除var

$height = $tmp_cont.height();

如果您想要一個全局變量,請不要使用var ,或者更明確地:

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

或者如果你仍然希望它是本地的,只需將其聲明為更高,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM