2016-07-05 38 views
-1

爲什麼return false退出$.each循環下面?

var Items = { 
    "5340071": { 
     "alt": "Sample text" 
    }, 
    "5333539": { 
     "alt": "Sample text" 
    }, 
    // Etc. 
}; 

var viewportBottom = $(window).height() + $(window).scrollTop(); 
$.each(Items, function(itemId, objItem) {  
    $("<img src='/img/1503/4/" + itemId + ".jpg?h=150'>").on('load', function() { 
     $(document.body).append($(this)); 
     var imageTop = $(this).offset().top; 
     if (imageTop > viewportBottom) { 
      console.log('Exit loop'); // Text is printed in console 
      return false;    // This should break the $.each loop, but it doesn't 
     } 
    }); 
}); 

請指教。

+0

@ T.J.Crowder它在'for'中工作,我假設它適用於'$ .each' :) – guradio

+2

@guradio:它們是完全不同的東西。 –

回答

0

該代碼中沒有return false從回調到$.each。在on附加的事件處理程序中有一個return false

通常當你有一個嵌套的回調你想影響一個外部循環,你可以設置一個標誌,並檢查它在外部循環;但是在這裏是不可能的,因爲在處理程序被調用的時候,循環已經很久了。

如果您的目標是在填充視口之前添加圖像,則不能使用$.each,因爲您不知道何時停止,直到圖像加載,這是異步發生的。這很好,我們可以在前一個結束時觸發加載下一個。

var Items = { 
    "5340071": { 
     "alt": "Sample text" 
    }, 
    "5333539": { 
     "alt": "Sample text" 
    }, 
    // Etc. 
}; 

var viewportBottom = $(window).height() + $(window).scrollTop(); 
var index = 0; 
var itemIds = Object.keys(Items); 
loadNextImage(); 
function loadNextImage() { 
    // Get this item ID 
    var itemId = itemIds[index++]; 

    // Get the alt text for it 
    var alt = Items[itemId].alt; 

    // Create the image WITHOUT a src 
    var img = $("<img>"); 

    // Apply the alt text 
    if (alt) { 
     img.attr("alt", alt); 
    } 

    // Hook the load handler BEFORE we set src 
    img.one('load', function() { 
     // Append the image to the body 
     img.appendTo(document.body); 

     // Do we have more? 
     if (index < Items.length) { 
      // Do we have room for more? 
      var imageTop = img.offset().top; 
      if (imageTop <= viewportBottom) { 
       // Yes, load the next one 
       loadNextImage(); 
      } 
     } 
    }); 

    // Now set the src 
    img.attr("src", "/img/1503/4/" + itemId + ".jpg?h=150"); 
} 

還要注意的一點關於src以上,以前的代碼有可能突然出現,如果圖像是在緩存中的競爭條件。

而你沒有使用alt文本,所以我在上面添加了。

+0

但如何重寫代碼以使其工作?我已經嘗試過一面旗幟,但這也不起作用。 – Martin

+0

@Martin:我不能告訴你如何使它工作,因爲據我所知,你試圖做的事情是不可能的。您正試圖在未來發生事件(圖像加載回調)影響當前的循環。該代碼的實際目標是什麼?只能追加儘可能多的圖像? –

+0

@Martin:如果是這樣,我發佈了一個更新,應該讓你以正確的方式。 –