2015-11-19 71 views
0

所有圖像均由ajax負載。有時它是完美的,但通常它不工作正確 - 看看screen,所有的圖像相互重疊。我的錯在哪裏?我會重構這段代碼,當我解決這個問題:)。後端:Ruby on Rails。砌體ajax負載無法正常工作

JS:

$(document).ready(function() { 
    (function() { 
    $.ajax({ 
     url: '/photos?page=' + 1, 
     type: 'get', 
     dataType: 'script', 
     success: function(data) { 
     var $container = $('#photo-container'); 
     var items = JSON.parse(data); 

     items.forEach(function(item) { 
      var img = $('<img src="' + item.image.url + '" />'); 
      var elem = $('<div class="grid__item"><img src="' + item.image.url + '" /></div>'); 
      $container.append(elem); 
     }); 

     initMasonry(); 
     initInfiniteScroll(); 
     } 
    }); 
    }()); 
}); 

function initMasonry() { 
    var $container = $('#photo-container'); 

    $container.masonry({ 
    gutter: 20, 
    itemSelector: '.grid__item', 
    columnWidth: 300 
    }); 
} 

function initInfiniteScroll() { 
    var page = 1, 
    loading = false; 

    function nearBottomOfPage() { 
    return $(window).scrollTop() > $(document).height() - $(window).height() - 200; 
    } 

    $(window).scroll(function(){ 
    if (loading) { 
     return; 
    } 

    if(nearBottomOfPage()) { 
     loading=true; 
     page++; 
     $.ajax({ 
     url: '/photos?page=' + page, 
     type: 'get', 
     dataType: 'script', 
     success: function(data) { 
      var $container = $('#photo-container'); 
      var arr = JSON.parse(data); 

      arr.forEach(function(item) { 
      var img = $('<img src="' + item.image.url + '" />'); 
      var elem = $('<div class="grid__item"><img src="' + item.image.url + '" /></div>'); 

      $container.imagesLoaded(function() { 
       $container.append(elem).masonry('appended', elem, true).masonry('reloadItems'); 
      }); 
      }); 

      loading=false; 
     } 
     }); 
    } 
    }); 
} 

回答

0
success: function(data) { 
    var $container = $('#photo-container'); 
    var arr = JSON.parse(data); 
    var fragment = document.createDocumentFragment(); 
    var elems = []; 

    elems = arr.map(function(item) { 
    var $elem = $('<div class="grid__item"><img src="' + item.image.url + '" /></div>'); 
    $elem.hide(); 
    // get DOM element, not jQuery 
    var elem = $elem[0] 
    // add element, not jQuery, to fragment 
    fragment.appendChild(elem); 
    return elem 
    }); 
    // append elems to container 
    $container.append(fragment); 

    $container.imagesLoaded(function() { 
    // show items once all visible 
    $(elems).show(); 
    $container.masonry('appended', elems) 
    }); 

    loading=false; 
} 
0

我認爲你需要 「重新初始化」,它的每個阿賈克斯之後。您可以使用$ .ajaxConplete()