2016-11-08 96 views
0

我使用Active Admin將圖像上傳到我的應用,工作正常。但我希望上傳的圖像顯示在Bootstrap Carrousel中。我缺乏使用Rails和Javascript的經驗限制了我獲得我想要的結果。在Rails 4中動態添加圖像到Bootstrap Carousel應用

JavaScript控制檯拋出回這個錯誤:

carousel.self-e47323f….js?body=1:148 Uncaught TypeError: Cannot read property 'offsetWidth' of undefined(…) 
    Carousel.slide @ carousel.self-e47323f….js?body=1:148 
    Carousel.next @ carousel.self-e47323f….js?body=1:110 
    (anonymous function) @ carousel.self-e47323f….js?body=1:186 
    each @ jquery.self-bd7ddd3….js?body=1:371 
    each @ jquery.self-bd7ddd3….js?body=1:138 
    Plugin @ carousel.self-e47323f….js?body=1:178 
    clickHandler @ carousel.self-e47323f….js?body=1:218 
    dispatch @ jquery.self-bd7ddd3….js?body=1:5227 
    elemData.handle @ jquery.self-bd7ddd3….js?body=1:4879 

編輯 我看着可能重複,我可以看到,這可能是一個可能的重複,但我不確定如何我將我的Ruby loop整合到javascript中。

有人可以提醒我。代碼如下

編輯更新代碼

<div id="carousel-example-generic" class="carousel slide" data-ride="carousel"> 
<!-- Indicators --> 
<ol class="carousel-indicators"> 
    <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li> 
    <li data-target="#carousel-example-generic" data-slide-to="1"></li> 
    <li data-target="#carousel-example-generic" data-slide-to="2"></li> 
</ol> 

<!-- Wrapper for slides --> 
    <div class="carousel-inner" role="listbox"> 

    <% @product.photos.each_with_index do |photo, index| %>      
    <div class="item #{"active" if index.zero? }"> 
    <%= image_tag(photo.image.url(:large)) %>      
    </div> 
    <% end %> 

    ... 
    </div> 

    <!-- Controls --> 
    <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev"> 
    <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> 
    <span class="sr-only">Previous</span> 
    </a> 
    <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next"> 
    <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"> </span> 
    <span class="sr-only">Next</span> 
    </a> 
</div> 

<script type="text/javascript"> 
    $('.carousel').carousel({ 
    interval: 2000 
    }) 
</script> 
+1

[使用jQuery動態添加幻燈片到Bootstrap 3輪播](http://stackoverflow.com/questions/24177572/add-slides-to-bootstrap-3-carousel-dynamically-using-jquery) –

回答

0

也許你將缺少類「主動」或類「主動」被添加到所有項目。將「活動」類添加到要首先顯示的照片上。

下面的代碼會將類'active'添加到第一個圖像。

<% @product.photos.each_with_index do |photo, index| %>      
    <div class="item #{"active" if index.zero? }"> 
    <%= image_tag(photo.image.url(:large)) %>      
    </div> 
<% end %> 

此外,請檢查您的網頁上的JavaScript錯誤。

+0

謝謝,但它不工作,我在'JS控制檯'中得到這個錯誤:'carousel.self-e47323f ... .js?body = 1:148 Uncaught TypeError:無法讀取undefined(...)的屬性'offsetWidth' – Slowboy

+0

您能請檢查這個[url](http://stackoverflow.com/questions/29027830/getting-cannot-read-property-offsetwidth-of-undefined-with-bootstrap-carousel)對你有幫助嗎? – sssskkk

+0

我不確定它是否有幫助,url中的答案表明調用'active',但這就是循環所做的。也許'url'中的其他一些建議可以起作用。 – Slowboy

相關問題