Define owl carousel parameters in HTML (with class

2019-09-03 07:46发布

I have a page with few owl carousels. I would like to be able to set some parameters for these owl carousels in HTML code (using a class or data attribute).

Assuming I have two data attributes defined in my HTML, I have created following jQuery code:

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

And as you may expect it is not working. The parameters from first owl carousel are applied to all carousels. I have no idea how to make it work. Below is a fiddle with my attempt.

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

I would be very grateful for anyone that is able to fix it for me. Thanks in advance

2条回答
爷的心禁止访问
2楼-- · 2019-09-03 08:36

Should be:

$(".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
    });
});
查看更多
唯我独甜
3楼-- · 2019-09-03 08:38

Here is an easier way to use data attributes with the 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) );

Your HTML would look like this:

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

In the example above, I've defined some default options in my defaults variable, and then I override them with the data attributes as well as added a few more.

This is possible by using jQuery.extend(). Documentation can be found here: https://api.jquery.com/jquery.extend/

查看更多
登录 后发表回答