我试图在不同的函数中使用变量,我想设置全局变量。有办法怎么做?
我想要这样的事情:
$('.bar1').animate({'height':'10' + "%"},1500, function() {
var bar1_height = $(".bar1").height() * 0.5;
});
然后在其他地方使用变量bar1_height
。
答案 0 :(得分:5)
在您的函数之外声明bar_height
。
var bar1_height;
$('.bar1').animate({'height':'10' + "%"},1500, function() {
bar1_height = $(".bar1").height() * 0.5;
});
这将允许您全局访问它(即函数内部和外部)。
来自MDN:
当你在任何函数之外声明一个变量时,它被称为a 全局变量,因为它可用于任何其他代码 目前的文件。在函数中声明变量时,它是 称为局部变量,因为它只在其中可用 功能
答案 1 :(得分: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;
});
答案 2 :(得分:1)
javascript的最差方面之一是implied global scope。您可以通过删除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');
你能发现可怕的虫子吗? jsFiddle
你应该尽可能在最窄的范围内声明你的变量,否则你最终会得到一个令人困惑的全局变量。如果你需要一个函数内外的变量,你应该在外部范围内声明它(正如其他答案所说的那样):
(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);
})();
(这里神秘的外部功能是阻止变量变为真正的全局变量。)
我发现this blog post对于理解有关变量范围的最佳实践非常有用。