在Rails 4应用程序中动态地向Bootstrap Carousel添加图像

Dynamically Adding images to Bootstrap Carousel in Rails 4 app

本文关键字:Bootstrap Carousel 添加 图像 动态 Rails 应用程序      更新时间:2023-09-26

我使用Active Admin上传图像到我的应用程序,这是工作良好。但我希望上传的图像显示在一个引导旋转木马。我缺乏使用Rails和Javascript的经验,限制了我得到我想要的结果。

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>

可能您将错过'active'类或'active'类已添加到所有项中。将类'active'添加到想要首先显示的照片中。

下面的代码将类'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错误