Bootstrap 4 Dynamic Carousel using Jquery

2019-08-19 00:29发布

I'm trying to add images dynamically to a Bootstrap Carousel but it just shows them in a list (https://i.imgur.com/8lOOg3w.jpg).

The images are National Parks Service API urls (https://www.nps.gov/common/uploads/structured_data/3C86AAE7-1DD8-B71B-0BA8BC5E5E895E98.jpg).

Here's the HTML

<div id="carousel" class="carousel slide" data-ride="carousel">
    <!-- Indicators -->
    <ol class="carousel-indicators"></ol>
    <!-- Wrapper for slides -->
    <div class="carousel-inner"></div>
    <!-- Controls -->
        <a class="carousel-control-prev" href="#demo" data-slide="prev">
        <span class="carousel-control-prev-icon"></span>
        </a>
    <a class="carousel-control-next" href="#demo" data-slide="next">
        <span class="carousel-control-next-icon"></span>
    </a>
</div>

and JS

$(document).ready(function(){
for(let j = 0; j < parkInfo.data[i].images.length; j++) {
  $('<div class="item"><img src="'+parkInfo.data[i].images[j].url+'" width="50%">   </div>').appendTo('.carousel-inner');
  $('<li data-target="#carousel" data-slide-to="'+j+'"></li>').appendTo('.carousel-indicators')

}
  $('.item').first().addClass('active');
  $('.carousel-indicators > li').first().addClass('active');
  $('#carousel').carousel();
});

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-08-19 01:09

Looks like you need to have a class on the item 'carousel-item' not 'item'.

https://jsfiddle.net/orb9945u/

$(document).ready(function(){
    for(let j = 0; j < 5; j++) {
        $('<div class="carousel-item"><img 
          src="https://loremflickr.com/320/240" width="50%">   
          </div>').appendTo('.carousel-inner');
        $('<li data-target="#carousel" data-slide-to="'+j+'"> 
          </li>').appendTo('.carousel-indicators')

    }

    $('.carousel-item').first().addClass('active');
    $('.carousel-indicators > li').first().addClass('active');
    $('#carousel').carousel();
});
查看更多
登录 后发表回答