1

我正在尝试在不同的函数中使用变量,我想设置全局变量。有没有办法怎么做?

我想要这样的东西:

$('.bar1').animate({'height':'10' + "%"},1500, function() {  
    var bar1_height = $(".bar1").height() * 0.5;  
});

然后bar1_height在别处使用变量。

4

3 回答 3

6

bar_height在你的函数之外声明。

var bar1_height;
$('.bar1').animate({'height':'10' + "%"},1500, function() {
    bar1_height = $(".bar1").height() * 0.5;
});

这将允许您在全局范围内访问它(即在您的函数内部和外部)。

来自MDN

当您在任何函数之外声明变量时,它被称为全局变量,因为它可用于当前文档中的任何其他代码。在函数中声明变量时,它称为局部变量,因为它仅在该函数中可用。

于 2012-06-27T18:34:51.460 回答
1
$('.bar1').animate({'height':'10' + "%"},1500, function() {  
    window.bar1_height = $(".bar1").height() * 0.5;  
});

完毕。

或者更理想的方式

var bar1_height;
$('.bar1').animate({'height':'10' + "%"},1500, function() {  
    bar1_height = $(".bar1").height() * 0.5;  
});
于 2012-06-27T18:35:24.370 回答
1

javascript最糟糕的方面之一是隐含的全局范围。您可以通过删除var关键字来使变量全局化:

$('.bar1').animate({'height':'10' + "%"},1500, function() {  
   bar1_height = $(".bar1").height() * 0.5;  
});

但这被认为是非常 糟糕的 做法。例如:

var getAddress = function(street, city, country) {
    location = street + ', ' + city + ', ' + country;
    return location;
}
getAddress('Holborn', 'London', 'England');

你能发现可怕的错误吗?js小提琴

你真的应该在尽可能窄的范围内声明你的变量,否则你最终会得到一团混乱的全局变量。如果您在函数内部和外部都需要一个变量,您应该简单地在外部范围内声明它(正如其他答案所说):

(function () {
    var bar1_height;

    $('.bar1').animate({'height':'10' + "%"},1500, function() {
        // Use variable from outer scope  
        bar1_height = $(".bar1").height() * 0.5; 
    }); 

    // Variable still has its value here
    alert(bar1_height);
})();

(这里神秘的外层功能是防止变量成为真正的全局变量。)

我发现这篇博文对于理解有关变量范围的最佳实践非常有用。

于 2012-06-27T18:48:56.543 回答