在Owl Carousel 2中加载动态内容 [英] Load dynamic content in Owl Carousel 2

查看:1015
本文介绍了在Owl Carousel 2中加载动态内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有2个轮播的网页,其中我必须根据用户的操作显示不同的项目.

I have a webpage with 2 carousels in which I have to show different items depending on user actions.

新数据来自互联网,我使用fetch,将json解析为数组,一切都很好.

The new data comes from the internet, I use fetch, parse the json into an array, all good.

唯一的问题是我不能用新物品代替轮播中的旧物品.

Only problem is I can't have the new items replace the old ones in the carousel.

我尝试过一个简单的例子

For a simple example I have tried

var carousel = $jq("#owl-genres");
for(...) {
   carousel.owlCarousel()
       .trigger('add.owl.carousel', [$jq('<div class="item">' + genres[i] + '</div>')])
       .trigger('refresh.owl.carousel');
}

但是什么也没发生.尽管方法已执行且.trigger已执行,但仍保留了旧元素.

but nothing happens. The old elements remains, although the methods executes and the .trigger is executed.

我也尝试过

for(...) {
   content += '<div class=\'item\'>' + genres[i] + '</div>'
   carousel.html(content)
}
carousel.owlCarousel().trigger('refresh.owl.carousel');

确实将新物品添加到轮播中,但是它们现在是垂直堆叠的,导航无法正常工作,我想整个轮播都坏了.

which indeed adds the new items to the carousel but they are now vertically stacked, the navigation doesn't work, I guess the whole carousel is broken.

那么替换Owl Carousel 2中的物品的正确方法是什么?

So what's the correct way to replace the items in Owl Carousel 2?

推荐答案

基于 https://stackoverflow.com/a/的解决方案37862372/4249825

所有这些都可以放在一个函数中,该函数接收要显示的新元素数组,并在我们获取新数据后立即执行. 希望对其他人有帮助(我看到有很多关于此的问题...)

This can all be put in a function which receives the new array of elements to display and be executed as soon as we fetch new data. Hope it will help others (I saw there are many questions about this...)

//these 3 lines kill the owl, and returns the markup to the initial state
carousel.trigger('destroy.owl.carousel'); 
carousel.find('.owl-stage-outer').children().unwrap();
carousel.removeClass("owl-center owl-loaded owl-text-select-on");

// add the new items 
for (var i = 0; i < genres.length; i++) { 
     content += "<div class=\"item\">" + genres[i] + "</div>"
}
carousel.html(content);

//reinitialize the carousel (call here your method in which you've set specific carousel properties)
carousel.owlCarousel();

这篇关于在Owl Carousel 2中加载动态内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆