我试图添加每张图片的大小,因此它保存在一个变量中。到目前为止我有这个:
var totalHeight;
var addHeight = $(this).height();
$('.img').each(function(i){
totalHeight = totalHeight + addHeight;
console.log(totalHeight);
});
http://jsfiddle.net/tmyie/dKjcc/1/
但是,console.log正在报告NaN
。有谁知道为什么?
答案 0 :(得分:5)
var totalHeight = 0;
$('.img').each(function(i){
totalHeight += $(this).height();
});
进一步说明:您想要使用的 this 是与选择器“.img”匹配的元素。你现在拥有的,var addHeight = $(this).height()是全局对象窗口的(高度)
console.log(this === window);
了解使用关键字this at MDN或learn jQuery
答案 1 :(得分:0)
您需要设置var totalHeight = 0;
答案 2 :(得分:0)
走你最初去的路线:
var totalHeight = 0;
$('.img').each(function(index, element){
totalHeight = totalHeight + element.clientHeight;
});
答案 3 :(得分:0)
普通JavaScript:
function heights(element)
{
var sum = 0;
for (var i = 0; i < element.length; i++)
{
sum += element[i].clientHeight;
}
document.write(sum);
return sum;
}
var imageArr = document.getElementsByClassName('img');
heights(imageArr);
答案 4 :(得分:-2)
Try this
<pre><code>
var totalHeight=0;
var addHeight = $(this).height();
$('.img').each(function(i){
totalHeight = totalHeight + addHeight;
console.log(totalHeight);
});
</pre></code>