代码之家  ›  专栏  ›  技术社区  ›  Atif

jQuery函数外部的变量作用域

  •  8
  • Atif  · 技术社区  · 14 年前

    我试图在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 未定义。我怎样才能保留 $高度 ?

    1 回复  |  直到 9 年前
        1
  •  17
  •   Nick Craver    14 年前

    你可以把 var 这样地:

    $height = $tmp_cont.height();
    

    如果需要全局变量,请将 风险价值 ,或者更明确地说:

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