2011-05-15 125 views
16

如何獲取每個元素的寬度並將其總結出來?jQuery:獲取每個元素的寬度並將它們相加

舉例來說,這裏是HTML:

<div id="container"> 
<div class="block-item" style="width:10px"></div> 
<div class="block-item" style="width:50px"></div> 
<div class="block-item" style="width:90px"></div> 
<div> 

我想通過每一個元素循環的,但我怎麼了概括的數字?

$('.block-item').each(function(index) { 
    alert($(this).width()); 
}); 

我想要得到的總數爲150 (10 + 50 + 90)

謝謝。

回答

24

使用parseInt(value, radix)

var totalWidth = 0; 

$('.block-item').each(function(index) { 
    totalWidth += parseInt($(this).width(), 10); 
}); 

這裏是一個example fiddle

+1

可能想要一個+ =收藏家,是嗎? – 2011-05-15 01:49:49

+0

@Alex謝謝,當我創作小提琴時,我自己發現了這個愚蠢的錯字。 – 2011-05-15 01:52:19

+0

謝謝你的幫助! :-) – laukok 2011-05-15 02:07:06

2
var w = GetWidths('.block-item'); 

function GetWidths(id) { 
    var i = 0; 

    $(id).each(function (index) { 
     i += parseInt($(this).width(), 10); 
    }); 

    return i; 
} 
+0

清潔和優雅地使用變量和函數彼此。 – 2016-08-16 13:42:13

相關問題