我正在尝试在我的网站上添加多个swipers(http://www.idangero.us/swiper/)。我想添加动态的swipers,所以我为每个swiper使用相同的类。每个swiper看起来像这样:
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide">
Slide 1
</div>
<div class="swiper-slide">
Slide 2
</div>
<div class="swiper-slide">
Slide 3
</div>
<div class="swiper-slide">
Slide 4
</div>
</div>
<!-- Add Pagination -->
<div class="swiper-pagination"></div>
<!-- Add Arrows -->
<div class="swiper-button-next"></div>
<div class="swiper-button-prev"></div>
</div>
如果我想初始化一个swiper,这个代码一切正常:
var swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
paginationClickable: '.swiper-pagination',
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
loop: true
});
我想要的是在一个页面上实例化多个swipers,如下所示:
var swipes = [];
$('.swiper-container').each(function(i, obj){
swipes[i] = new Swiper(obj, {
pagination: '.swiper-pagination',
paginationClickable: '.swiper-pagination',
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
loop: true
});
});
但这对我不起作用。我认为这些特性导致了问题。也许我应该做这样的事情来更具体,只是在当前的swiper中使用pagination / nextButton / ...而不是在整个网站上:
pagination: obj + '.swiper-pagination',
paginationClickable: obj + '.swiper-pagination',
nextButton: obj + '.swiper-button-next',
...
但我不知道该怎么做。我怎么能这样做?
答案 0 :(得分:9)
你需要做以下事情:
$('.swiper-container').each(function(){
new Swiper($(this), {
pagination: $(this).find('.swiper-pagination'),
paginationClickable: $(this).find('.swiper-pagination'),
nextButton: $(this).find('.swiper-button-next'),
prevButton: $(this).find('.swiper-button-prev'),
loop: true
});
});
$('.swiper-container').each(function(){
new Swiper($(this), {
pagination: $(this).find('.swiper-pagination'),
paginationClickable: $(this).find('.swiper-pagination'),
nextButton: $(this).find('.swiper-button-next'),
prevButton: $(this).find('.swiper-button-prev'),
loop: true
});
});