gpt4 book ai didi

javascript - each() 函数中 jqueryeach() 函数的返回值和作用域

转载 作者:行者123 更新时间:2023-12-02 19:21:42 25 4
gpt4 key购买 nike

我有这样的标记:

<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 保持为零。我意识到这是 super 初学者:)非常感谢所有帮助。

http://jsfiddle.net/m2aJu/

最佳答案

您不需要返回allestHeight,将其删除即可工作。

并将第二个内的 vartalestHeight = thisSlideHeight; 更改为 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);
});

And here is the working demo

关于javascript - each() 函数中 jqueryeach() 函数的返回值和作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12469442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com