【问题标题】:return and scope for jquery each() function within an each() functioneach() 函数中 jquery each() 函数的返回和作用域
【发布时间】:2012-09-10 06:29:22
【问题描述】:

我有这样的标记:

<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/

【问题讨论】:

    标签: javascript jquery scope each


    【解决方案1】:

    你不需要return tallestHeight,删除它就可以了。

    将var tallestHeight = 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。

    【讨论】:

    • var tallestHeight = thisSlideHeight;
    • @zerkms 是的,我看到了var :)
    • 有点离题,但仍然相关:javascript 只做函数范围,而不是块范围。它还具有提升功能,将声明提升到范围(即函数)的顶部,因此虽然出于美学原因应该删除内部的 var 从技术上讲,该函数仍将保持不变:gist.github.com/3740886
    猜你喜欢
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    • 2011-10-19
    • 2014-07-27
    • 1970-01-01
    • 2014-06-26
    相关资源
    最近更新 更多