2014-10-03 76 views
0

我使用簡單的ajax調用來從sharepoint列表中獲取某些信息並從中創建輪播。jQuery .on()從列表中動態創建內容輪播

我想我需要使用.promise()或.on()爲了加載這個for循環已經通過列表後,所以我添加一個對象的旋轉木馬,但我失去了如何做到這一點。

這是我的循環看起來像。它確實獲得了所有的數據。

for (var i = 0; i < data.d.results.length; i++) { 
        response = '<article class="item"><img src="' + data.d.results[i].Image_x0020_URL + '"><div class="carousel-caption"><h3>' + data.d.results[i].Title + '</h3><p>' + data.d.results[i].Content + '</p><p><a class="btn btn-info btn-sm">Read More</a></p></div></article>'; 
        indicator = '<li data-target="#myCarousel" data-slide-to="'+i+'" class="active"></li>'; 
       } 

後for循環,我我的信息附加到我的旋轉木馬:

$('#homepageItems').append(res); 
$('#indicators').append(ind); 

我的旋轉木馬代碼:

<div id="myCarousel" class="carousel slide"> 
    <div class="carousel-inner" id="homepageItems"> 
     <!-- Indicators --> 
    <ol class="carousel-indicators" id="indicators"> 
    </ol> 
    <div class="carousel-controls"> <a class="carousel-control left" href="#myCarousel" data-slide="prev"> <span class="fa fa-angle-double-left"></span> </a> <a class="carousel-control right" href="#myCarousel" data-slide="next"> <span class="fa fa-angle-double-right"></span> </a> </div> 
    </div> 
</div> 

我已經添加了對循環到varible:

var loop = function(){forloop in here} 

然後加入

$.when(loop()).done().... 

這確實循環了所有的結果,並告訴我,當通過警報(「完成」)觸發;我把時間放在裏面,但旋轉木馬不渲染。

如何在for循環完成後將對象加載到傳送帶上?

回答

1

您不需要.on來創建傳送帶。

看到這個問題的答案:Bootstrap Carousel with dynamic items does not slide

所以你以後的循環,你只是這樣做:

$.ajax({ 
    url: '/carousel', 
    dataType: 'json', 
    success: function(data) { 
     var response = '', 
      indicator = ''; 
     for (var i = 0; i < data.d.results.length; i++) { 
      response += '<div class="item"><img src="' + data.d.results[i].Image_x0020_URL + '"><div class="carousel-caption"><h3>' + data.d.results[i].Title + '</h3><p>' + data.d.results[i].Content + '</p><p><a class="btn btn-info btn-sm">Read More</a></p></div></div>'; 
      indicator += '<li data-target="#myCarousel" data-slide-to="'+i+'"></li>'; 
     } 
     $('#homepageItems').append(response); 
     $('#indicators').append(indicator); 

     // set up the first slide as "active" 
     $('.item').first().addClass('active'); 
     $('.carousel-indicators > li').first().addClass('active'); 
     $("#myCarousel").carousel(); 
    } 
}); 

Plunker here

+0

難道我不需要在for循環中發生追加嗎? – jasonflaherty 2014-10-03 15:52:47

+0

一旦這張幻燈片從幻燈片1滑動到2幻燈片消失? – jasonflaherty 2014-10-03 15:56:35

+0

爲什麼你使用'article'標籤而不是'div' - 不確定對傳送帶有什麼影響?如果使用開發人員工具/ Firebug停止滑動時檢查傳送帶,是否有動態添加的元素? – mccannf 2014-10-03 16:35:35