Carousel not working after adding items dynamically with jQuery

时间:2019-03-06 11:32:51

标签: jquery

I added images dynamically to carousel but they weren't worked. I only got images but not carousel format. this my code as shown below.

<div id="summeritems" class="popular-products-slides owl-carousel">
    <!-- Single Product -->

    <!-- End -->
</div>

// Jquery Code

items.forEach(function(item){
var result =  `<div class="single-product-wrapper">
 <div class="product-img">
  <img src="/image/${item.filename}" alt="">
  <div class="product-favourite">
    <a href="#" class="favme fa fa-heart"></a>
  </div>
</div>
<div class="product-description">
  <span>${item.metadata.brand}</span>
  <a href="single-product-details.html">
    <h6>${item.metadata.name}</h6>
  </a>
  <p class="product-price">LKR. 
  ${item.metadata.price}</p>
  <div class="hover-content">
    <!-- Add to Cart -->
    <div class="add-to-cart-btn">
      <a href="#" class="btn essence-btn">Add to 
      Cart</a>
    </div>
  </div>
</div>
</div>`
$('#summeritems').append(result); // Add Images to Navigation Slider

2 个答案:

答案 0 :(得分:0)

添加新元素后,您需要更新轮播。像这样:

var owl = $('#summeritems');
owl.owlCarousel();

// Your code
items.forEach(function(item){
  var result =  '... HTML of new elements ...';
  $('#summeritems').append(result); // Add Images to Navigation Slider
});

// update carousel at the end
owl.trigger('refresh.owl.carousel');

有关更多API官方文档的信息非常有用:Owl carousel API

答案 1 :(得分:0)

    items.forEach(function(item){

              v = '/image/'+item.filename;
              image_temp = new Image();
              image_temp.src = v;
              image_temp.onload = function(){
         $('#owl-sunny').owlCarousel().trigger('add.owl.carousel',
         [jQuery('<div class="owl-item"><a href="/'+ item.filename +'"><img src="'+ v +'"></a><div class="product-description"><span>' + item.metadata.brand + '</span><a href=""><h6>'+ item.metadata.name + '</h6></a><p class="product-price">LKR. ' + item.metadata.price + '</p></div></div>')]).trigger('refresh.owl.carousel');