Javascript 函数中jquery each()函数的返回和作用域
我很高兴有这样的标记:Javascript 函数中jquery each()函数的返回和作用域,javascript,jquery,scope,each,Javascript,Jquery,Scope,Each,我很高兴有这样的标记: <div class="imagegroup"> <img> <img> <img> </div> <div class="imagegroup"> <img> <img> <img> </div> <div class="imagegroup"> <img> <
<div class="imagegroup">
<img>
<img>
<img>
</div>
<div class="imagegroup">
<img>
<img>
<img>
</div>
<div class="imagegroup">
<img>
<img>
<img>
</div>
但我很困惑,如何将内部每个函数的结果“一级”传递到“外部”每个函数,而不只是设置一个全局变量<代码>最高高度在我写这篇文章时保持为零。我意识到这是超级初学者:)非常感谢大家的帮助
您不需要
返回最高高度
,将其移除即可工作
并更改var tallestHeight=thislideheight代码>至<代码>最高高度=此滑块高度在第二个变量中,您应该使用外部变量,而不是声明新变量
或者,您可以简化代码,如下所示:
$('.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);
});
var-tallestHeight=thislideheight@zerkms是的,我看到var
:)有点离题,但仍然相关:javascript只做函数作用域,而不是块作用域。它还具有提升功能,将声明提升到范围的顶部(即函数),因此,尽管出于美观原因应移除if中的var,但从技术上讲,函数仍将保持不变:
$('.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);
});