我正在使用Slick JS滑块,并且试图获取单击的幻灯片的索引。使用称为'getSlick'
下面的代码在单击幻灯片时记录所有索引。我只希望单击幻灯片的索引。我究竟做错了什么?
$('.sy-images-slides-primary .slick-slide').click(function(){
console.log($(".sy-images-slides-primary").slick("getSlick").$slides);
});
// // define inner slider
$('.slider').slick({
dots: false,
infinite: true,
slidesToShow: 5,
slidesToScroll: 5,
centerMode: true,
centerPadding: 110,
focusOnSelect: true,
variableWidth: true
});
$('.slider .slick-slide').click(function () {
$(".slider").slick("getSlick").$slides.each(function (index, slide) {
console.log(index);
});
});
.slick-slide {
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="//cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.css" rel="stylesheet" />
<script src="//cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.min.js"></script>
<div class="slider">
<div><img src="http://placehold.it/50x50"></div>
<div><img src="http://placehold.it/50x50"></div>
<div><img src="http://placehold.it/50x50"></div>
<div><img src="http://placehold.it/50x50"></div>
<div><img src="http://placehold.it/50x50"></div>
<div><img src="http://placehold.it/50x50"></div>
<div><img src="http://placehold.it/50x50"></div>
<div><img src="http://placehold.it/50x50"></div>
<div><img src="http://placehold.it/50x50"></div>
<div><img src="http://placehold.it/50x50"></div>
</div>
答案 0 :(得分:1)
如果要在单击幻灯片后立即执行此操作,请使用插件事件“ afterChange”,而不要像执行此操作那样使用额外的单击侦听器。
$('.your-element').on('afterChange', function(event, slick, currentSlide){
//
});
其中currentSlide是最后一个滑动元素的索引。
如果您需要一个侦听器来单击幻灯片本身,则可以从数据属性中读取位置(您必须标准化该值,因为该值也为-1,但这应该很容易工作)。>
您更改的代码:
// // define inner slider
$('.slider').slick({
dots: false,
infinite: true,
slidesToShow: 5,
slidesToScroll: 5,
centerMode: true,
centerPadding: 110,
focusOnSelect: true,
variableWidth: true
});
$('.slider').on('afterChange', function (event, slick, currentSlide) {
console.log('afterChange, currentSlide: ', currentSlide);
});
$('.slick-slide').on('click', function(ev){
console.log('onClick slick-index:', $(ev.currentTarget).data('slick-index'));
});
.slick-slide {
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="//cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.css" rel="stylesheet" />
<script src="//cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.min.js"></script>
<div class="slider">
<div><img src="http://placehold.it/50x50"></div>
<div><img src="http://placehold.it/50x50"></div>
<div><img src="http://placehold.it/50x50"></div>
<div><img src="http://placehold.it/50x50"></div>
<div><img src="http://placehold.it/50x50"></div>
<div><img src="http://placehold.it/50x50"></div>
<div><img src="http://placehold.it/50x50"></div>
<div><img src="http://placehold.it/50x50"></div>
<div><img src="http://placehold.it/50x50"></div>
<div><img src="http://placehold.it/50x50"></div>
</div>