在HTML中定义owl carousel参数(具有类或数据属性)

时间:2014-10-20 09:37:35

标签: html owl-carousel

我有一个很少有猫头鹰旋转木马的页面。我希望能够在HTML代码中为这些owl轮播设置一些参数(使用类或数据属性)。

假设我在HTML中定义了两个数据属性,我创建了以下jQuery代码:

$(".owl-carousel").each(function( index ) {
    var items_no = $(this).data('slides');
    var autoplay = $(this).data('autoplay');
    $(".owl-carousel").owlCarousel({
        items : items_no,
        autoplay: autoplay
    });
});

正如您所料,它无效。来自第一个猫头鹰转盘的参数适用于所有转盘。我不知道如何使它工作。下面是我尝试的小提琴。

http://jsfiddle.net/t2gj8eg2/4/

对于能够为我解决问题的人,我将非常感激。提前致谢

2 个答案:

答案 0 :(得分:3)

应该是:

$(".owl-carousel").each(function (index) {
    var items_no = $(this).data('slides');
    var autoplay = $(this).data('autoplay');
    $(this).owlCarousel({ // use $(this)
        items: items_no,
        autoplay: autoplay
    });
});

答案 1 :(得分:2)

以下是使用Owl Carousel的数据属性的简单方法:

  var oc = $('.owl-carousel');
  var ocOptions = oc.data('carousel-options');
  var defaults = {
    loop:            true,
    nav:             false,
    autoplay:        true,
  }
  oc.owlCarousel( $.extend( defaults, ocOptions) );

您的HTML将如下所示:

<div class="owl-carousel" data-carousel-options='{"autoplay":"true","autoplayTimeout":"6000","items":"2"}'> ... </div>

在上面的示例中,我在defaults变量中定义了一些默认选项,然后使用数据属性覆盖它们,并添加了一些。

使用jQuery.extend()可以做到这一点。可以在此处找到文档:https://api.jquery.com/jquery.extend/