问题
I have implement Owl carousel in Magnific Popup. and, It is normaly working fine. if, I have use simple function $('.owl-carousel').owlCarousel({autoplay:true, items:1})
but, Owl carousel does not work when i define Owl carousel with data attribute.
HTML:
<a class="ajax-popup btn btn-dark" href="ajaxproject.html">Click To Open Popup</a>
ajaxproject.html file:
<div class="container ajax-container">
<h2 class="text-7 text-center mb-4">Title 1</h2>
<div class="row">
<div class="col-sm-7">
<div class="owl-carousel owl-theme" data-autoplay="true" data-items="1">
<div class="item"> <img class="img-fluid" alt="" src="images/bg/image-6.jpg"> </div>
<div class="item"> <img class="img-fluid" alt="" src="images/bg/image-5.jpg"> </div>
</div>
</div>
<div class="col-sm-5">
<h4 class="text-4 font-weight-600">Description:</h4>
<p>Lisque persius interesset his et, in quot quidam persequeris vim, ad mea essent possim iriure. Lisque persius interesset his et, in quot quidam persequeris vim, ad mea essent possim iriure.</p>
</div>
</div>
</div>
Define owl carousel with data attribute: But, this is not working. What is wrong here?
$(".ajax-popup").magnificPopup({
type: "ajax",
mainClass: "mfp-fade",
closeBtnInside: true,
gallery: {
enabled: true,
},
callbacks: {
ajaxContentAdded: function() {
$(".owl-carousel").each(function (index) {
var items = $(this).data('slides');
var autoplay = $(this).data('autoplay');
$(this).owlCarousel({
items: items,
autoplay: autoplay
});
});
}
}
});
It is working fine. if I have use Define owl carousel without data attribute:
$(".ajax-popup").magnificPopup({
type: "ajax",
mainClass: "mfp-fade",
closeBtnInside: true,
gallery: {
enabled: true,
},
callbacks: {
ajaxContentAdded: function() {
$('.owl-carousel').owlCarousel({
autoplay:true,
items:1
})
}
}
});
回答1:
To access data-* attributes you need to use .attr()
not .data()
. Your code should be:
$(".ajax-popup").magnificPopup({
type: "ajax",
mainClass: "mfp-fade",
closeBtnInside: true,
gallery: {
enabled: true,
},
callbacks: {
ajaxContentAdded: function() {
$(".owl-carousel").each(function (index) {
var items = $(this).attr('data-items');
var autoplay = $(this).attr('data-autoplay');
$(this).owlCarousel({
items: items,
autoplay: autoplay
});
});
}
}
});
来源:https://stackoverflow.com/questions/58890465/define-owl-carousel-with-data-attribute-in-magnific-popup-callbacks-function