我正在尝试添加每个图像的大小,因此它保存在一个变量中。到目前为止我有这个:
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
。有谁知道为什么吗?
最佳答案
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
关于javascript - 将每个图像的大小相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22542375/