2017-08-21 20 views
0

我嘗試加載我創建一個函數的腳本,並將其添加到div =#職位,但足夠奇怪,這永遠不會添加項目檢索從服務器到div。結果是這樣的:http://imgur.com/a/ZmgGo元素沒有添加到正確的div與jquery-無限滾動

下面是腳本:

var $container = $('#posts'); 
function createPost(title, body, image, id) { 
    var x = '<div class="grid-item"><div class="blog-post"> <img src="https://placeimg.com/400/400/cba" alt=""> <h3>' + title + '</h3> <img src="' + image + '" alt=""> <a href="../Blog/SearchPartial/' + id + '" class="btn btn-primary">Reload </a> </div></div>"'; 
    $container.append(x) 
}; 

$(window).scroll(function() { 
    if ($(window).scrollTop() + $(window).height() == $(document).height()) { 
     alert("bottom!"); 
     InfiniteScroll(); 
    } 
}); 


var PageCount = 2; 
function InfiniteScroll() { 
    $.ajax({ 
     type: "GET", 
     url: "../api/posts/" + PageCount, 
     data: "{}", 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     success: function (data) { 

      if (data != "") { 
       $.each(data, function (i, post) { 
        createPost(post.Title, post.Body, post.Image, post.ID) 
       }); 
      } 
     }, 
     error: function (xhr) { 
      alert("error"); 
     } 
    }) 
    PageCount++; 
}; 

這裏是HTML:

<div id="posts"class="grid"> 
@foreach (var post in Model.Posts) 
{ 
    <div class="grid-item"> 
     <div class="blog-post"> 
      <img src="https://placeimg.com/400/400/cba" alt=""> 
      <h3>@post.Title</h3> 
      <img [email protected] alt=""> 

      <a href='@Url.Action("SearchPartial","Blog", new { postid = @post.ID })' class="button"> 
       Reload 
      </a> 
     </div> 
    </div> 
} 
</div> 
+0

如果它實際上沒有加載任何內容到'#posts',那麼你應該 - ** A - **檢查錯誤你的控制檯和** B - **檢查以確保'#posts'被加載到DOM中,然後將它分配給'$ container'變量 – Adjit

+0

並且json在哪裏? – Dekel

+0

@Adjit在控制檯中沒有錯誤,它加載它只是沒有在我不明白你的第二個選項 –

回答

0

砌築附加價值這是需要被封裝爲這樣對我的代碼X:

var x = '<div class="grid-item"> <div class="blog-post"> <img src="https://placeimg.com/400/400/cba" alt=""> <h3>' + title + '</h3> <img src="' + image + '" alt=""> <a href="../Blog/SearchPartial?postid=' + id + '" class="button">Read More </a> </div></div>"'; 

var $z = $(x); 
$grid.masonry() 
    .append($z) 
    .masonry('appended', $z) 
    .masonry();