开发者

jQuery set width of element to value of array

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜