2013-04-03 60 views
0

好日子計算高度和增加了可變

我有以下函數,計算每個div的高度,並將其添加到一個變量,但它不工作:

JS:

$('#latestInner, #make, #models').each(function() { 
    var i = 0; 
    var h = $(this).outerHeight(); 
    i = i + h; 
}); 
alert(i); 

HTML:

<div id="latestInner"></div> 
<div id="make"></div> 
<div id="models"></div> 

CSS:

#models {height: 100px; background: red;} 
#latestInner {height: 200px; background: green;} 
#make {height: 150px; background: blue;} 

FIDDLE:http://jsfiddle.net/uwsJH/7/

回答

2

您的問題是範圍界定。

試試這個小提琴:

http://jsfiddle.net/uwsJH/9/

i=0; 
$('#latestInner, #make, #models').each(function() { 
    // var i = 0; <--- wrong scope 
    var h = $(this).outerHeight(); 
    i = i + h; 
}); 
alert(i); 
+0

是的,非常感謝你 –

+0

不客氣;-) – Tschallacka

1

因爲我是一個局部variable.Try I = 0,而不是變種I = 0

+0

謝謝。在這種情況下什麼是局部變量? –

+0

http://sharkysoft.com/tutorials/jsa/content/031.html – cosset

0

你不需要每次初始化var i ......你可以這樣來做:

var i = 0; 
$('#latestInner, #make, #models').each(function() { 

    var h = $(this).outerHeight(); 
    i = i + h; 
    //Or simply 
    i = i + $(this).outerHeight(); 
}); 
alert(i); 
1

試試這個:

var i = 0; 
$('#latestInner, #make, #models').each(function() { 

var h = $(this).css("height"); 
i = i + h; 
});