I have some basic markup:
开发者_StackOverflow社区<div id="container">
<div class=".content"></div>
<div class=".content"></div>
<div class=".content"></div>
<div class=".content"></div>
<div class=".content"></div>
<div class=".content"></div>
</div>
and the following jQuery code:
var listWidth = [];
$('.content').each(function(){
listWidth.push($(this).width());
console.log(listWidth);
});
This returns:
[200, 540, 200, 540, 200, 540]
How do I set the width of the parent element to the sum of the values within the array, so in this case 2220?
Many thanks in advance.
Try this
var width = 0;
$.each(listWidth, function(){
width += this;
});
$("#container").width(width);
Perhaps something like this:
var divWidth = 0;
$(listWidth).each(function(){
divWidth += Number(this);
});
$('#container').css('width',divWidth);
精彩评论