jQuery:获取每个元素的宽度并将它们相加
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6005977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:12:54 来源:igfitidea点击:
jQuery: get each element's width and sum them up
提问by laukok
How can I get each element's width and sum them up?
我怎样才能得到每个元素的宽度并总结它们?
For instance, here is the HTML:
例如,这里是 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>
I can think of looping through each element, but how do I sum the numbers up?
我可以考虑遍历每个元素,但是如何对数字求和?
$('.block-item').each(function(index) {
alert($(this).width());
});
I want to get the total number of 150 (10 + 50 + 90)
.
我想获得150 (10 + 50 + 90)
.
Thanks.
谢谢。
回答by no.good.at.coding
var totalWidth = 0;
$('.block-item').each(function(index) {
totalWidth += parseInt($(this).width(), 10);
});
Here's an example fiddle.
这是一个示例 fiddle。
回答by Igor Krupitsky
var w = GetWidths('.block-item');
function GetWidths(id) {
var i = 0;
$(id).each(function (index) {
i += parseInt($(this).width(), 10);
});
return i;
}