@No_name404

Как подключить owl carousel к html, который генерируется из js файла?

Здравствуйте, у меня есть страница с карточкой товара. Каждая html структура товара генерируется из js файла, который берет характеристики товара из бд. В карточке товара я собираюсь сделать карусель картинок этого товара при помощи owl carousel 2. Названия картинок тоже находятся в бд. Я подключил плагин карусели, отлично работающий с html, который я написал на странице для проверки, но когда я подключил к html, генерируемой из js, то выводиться перестала даже html карусели.
Почему карусель не работает с html, который я получаю из js и возможно ли решить такую проблему?

Страница html:
<div class="container">
            <div class="row store">
                <div class="goods-out">
                </div>
            </div>
        </div>


js файл, из которого вывожу html карточки товара:
var out="";
            out+='<div class="col-lg-12 single">';
                out+='<div class="col-lg-7 prod-slides">';
                    out+='<div id="sync1" class="owl-carousel owl-theme">';
                        out+='<div class="item">';
                            out+='<h1>1</h1>';
                        out+='</div>';
                        out+='<div class="item">';
                           out+='<h1>1</h1>';
                        out+='</div>';
                        out+='<div class="item">';
                            out+='<h1>1</h1>';
                        out+='</div>';
                    out+='</div>';
                    
                    out+='<div id="sync2" class="owl-carousel owl-theme">';
                        out+='<div class="item">';
                            out+='<h1>1</h1>';
                        out+='</div>';
                        out+='<div class="item">';
                            out+='<h1>1</h1>';
                        out+='</div>';
                        out+='<div class="item">';
                            out+='<h1>1</h1>';
                        out+='</div>';
                    out+='</div>';
                    
                out+='</div>';
                
                out+='<div class="col-lg-5 prod-desc">';
                    out+=`<h1>${data.name}</h1>`;
                    out+='<hr>';
                    out+=`<h3>${data.cost} руб.</h3>`;
                    out+='<hr>';
                    out+=`<p>${data.description}</p>`;
                    out+='<hr>';
                    out+='<div>';
                        out+='<a href="#" class="pull-left">';
                                out+='<i class="fas fa-heart"></i>  Добавить в желаемое';
                        out+='</a>';
                    out+='</div>';
                    out+='<br>';
                    out+='<hr>';
                    out+='<div class="quant">';
                        out+='<div class="val-min"><i class="fas fa-minus"></i></div>';
                        out+='<div class="val"><span>2</span></div>';
                        out+='<div class="val-plus"><i class="fas fa-plus"></i></div>';            
                        out+='<a href="" class="ad-to-crt pull-right">Добавить в корзину</a>';
                    out+='</div>';
                out+='</div>';
            out+='</div>';
            
        $('.goods-out').html(out);

подключение в head:
<meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title><?=$title?></title>
        <link rel="icon" href="logo.png" type="image/x-icon" />
        <link rel="stylesheet" type="text/css" href="theme/bootstrap 3/css/bootstrap.css"/>
        <link rel="stylesheet" type="text/css" href="fontawesome/all.css"/>
        <link rel="stylesheet" href="slider/css/owl.carousel.css">
        <link rel="stylesheet" href="slider/css/owl.theme.default.css">
        <link rel="stylesheet" type="text/css" href="theme/css/main.css"/>


подключение скриптов и скрипт, инициирующий карусель:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>
        <script src="pages/productPage/js/product.js" type="text/javascript"></script>
        <script src="theme/bootstrap 3/js/bootstrap.js" type="text/javascript"></script>
        <script src="slider/js/owl.carousel.min.js" type="text/javascript"></script>
         <script  type="text/javascript">
          $(document).ready(function() {

  var sync1 = $("#sync1");
  var sync2 = $("#sync2");
  var slidesPerPage = 4; //globaly define number of elements per page
  var syncedSecondary = true;

  sync1.owlCarousel({
    items : 1,
    slideSpeed : 2000,
    nav: true,
    autoplay: true,
    dots: true,
    loop: true,
    responsiveRefreshRate : 200,
    navText: ['<svg width="100%" height="100%" viewBox="0 0 11 20"><path style="fill:none;stroke-width: 1px;stroke: #000;" d="M9.554,1.001l-8.607,8.607l8.607,8.606"/></svg>','<svg width="100%" height="100%" viewBox="0 0 11 20" version="1.1"><path style="fill:none;stroke-width: 1px;stroke: #000;" d="M1.054,18.214l8.606,-8.606l-8.606,-8.607"/></svg>'],
  }).on('changed.owl.carousel', syncPosition);

  sync2
    .on('initialized.owl.carousel', function () {
      sync2.find(".owl-item").eq(0).addClass("current");
    })
    .owlCarousel({
    items : slidesPerPage,
    dots: true,
    nav: true,
    smartSpeed: 200,
    slideSpeed : 500,
    slideBy: slidesPerPage, //alternatively you can slide by 1, this way the active slide will stick to the first item in the second carousel
    responsiveRefreshRate : 100
  }).on('changed.owl.carousel', syncPosition2);

  function syncPosition(el) {
    //if you set loop to false, you have to restore this next line
    //var current = el.item.index;
    
    //if you disable loop you have to comment this block
    var count = el.item.count-1;
    var current = Math.round(el.item.index - (el.item.count/2) - .5);
    
    if(current < 0) {
      current = count;
    }
    if(current > count) {
      current = 0;
    }
    
    //end block

    sync2
      .find(".owl-item")
      .removeClass("current")
      .eq(current)
      .addClass("current");
    var onscreen = sync2.find('.owl-item.active').length - 1;
    var start = sync2.find('.owl-item.active').first().index();
    var end = sync2.find('.owl-item.active').last().index();
    
    if (current > end) {
      sync2.data('owl.carousel').to(current, 100, true);
    }
    if (current < start) {
      sync2.data('owl.carousel').to(current - onscreen, 100, true);
    }
  }
  
  function syncPosition2(el) {
    if(syncedSecondary) {
      var number = el.item.index;
      sync1.data('owl.carousel').to(number, 100, true);
    }
  }
  
  sync2.on("click", ".owl-item", function(e){
    e.preventDefault();
    var number = $(this).index();
    sync1.data('owl.carousel').to(number, 300, true);
  });
});
        </script>


css
#sync1 .item {
    background: #0c83e7;
    padding: 80px 0px;
    margin: 5px;
    color: #FFF;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;
    text-align: center;
}

#sync2 .item {
    background: #C9C9C9;
    padding: 10px 0px;
    margin: 5px;
    color: #FFF;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;
    text-align: center;
    cursor: pointer;
}

#sync2 .item  h1 {
      font-size: 18px;
}

.current .item{
  background: #0c83e7;
}

#sync2 .current .item{
    background: #0c83e7;
}

.owl-theme .owl-nav [class*='owl-'] {
    transition: all .3s ease;
}
.owl-theme .owl-nav [class*='owl-'] &.disabled:hover {
    background-color: #D6D6D6;
}

//arrows on first carousel
#sync1.owl-theme {
  position: relative;
}

#sync1.owl-theme .owl-next, .owl-prev {
    width: 22px;
    height: 40px;
    margin-top: -20px;
    position: absolute;
    top: 50%;
}
#sync1.owl-theme .owl-prev{
    left: 10px;
}
#sync1.owl-theme .owl-next{
    right: 10px;
}

Может у меня не в той последовательности скрипты подключены, но я как только не менял их местами.
Буду очень признателен за любые варианты!
  • Вопрос задан
  • 920 просмотров
Решения вопроса 1
@edk55
Для начала надо убедиться в том, что скрипт инициализации owl каруселии срабатывает после появления #sync1 и #sync2 в DOM, добавьте логгирование.

var sync1 = $("#sync1");
  var sync2 = $("#sync2");
  console.log(sync1);
  console.log(sync2);
  ...


По-хорошему, вызывать скрипт инициализации owl карусели следует после строки

$('.goods-out').html(out); 
...(вызов функции инициализации owl)


Кроме того, убедитесь, что в консоли нет никаких ошибок.
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
@Do-oN
$(document).ready(function(){
$("body").delegate('.owl-carousel','owlCarousel');
});
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы