开发者

jQuery set width of element to value of array

开发者 https://www.devze.com 2023-04-01 11:05 出处:网络
I have some basic markup: 开发者_StackOverflow社区<div id=\"container\"> <div class=\".content\"></div>

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

精彩评论

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