[英]return and scope for jquery each() function within an each() function
我有这样的标记:
<div class="imagegroup">
<img>
<img>
<img>
</div>
<div class="imagegroup">
<img>
<img>
<img>
</div>
<div class="imagegroup">
<img>
<img>
<img>
</div>
我想分别获得每组中最高图像的高度。 我在each
函数中都有一个jquery each
函数:
$('.imagegroup').each(function(index) {
var tallestHeight = 0;
var slideshowNumber = index;
var slides = $(this).children();
$(slides).each(function(index) {
thisSlideHeight = $(this).height();
console.log("In slideshow #" + slideshowNumber + ", slide #" + index + " has height " + thisSlideHeight);
if (thisSlideHeight > tallestHeight) {
var tallestHeight = thisSlideHeight;
}
return tallestHeight;
});
console.log("For slideshow " + slideshowNumber + " the tallest slide is " + tallestHeight);
});
但我很困惑的是如何将每个函数内部的“一级”结果传递到“外部”每个函数而不仅仅设置一个全局变量。 我写这篇tallestHeight
保持在零。 我意识到这是超级初学者:)所有帮助非常感谢。
你不需要return tallestHeight
,删除它就可以了。
并改变var tallestHeight = thisSlideHeight;
to tallestHeight = thisSlideHeight;
在第二个内部,你应该使用外部变量,而不是声明一个新变量。
或者您可以简化代码,如下所示:
$('.imagegroup').each(function(index) {
var max = Math.max.apply(null, $(this).find('img').map(function() {
return $(this).height();
}));
console.log("For slideshow " + index + " the tallest slide is " + max);
});
这是工作演示 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.