iDangero.us Swiper multiple instances

2020-03-24 08:09发布

问题:

I'm trying to add multiple swipers (http://www.idangero.us/swiper/) on my site. I want to add the swipers dynamic so i use the same class for every swiper. Each swiper looks like this:

    <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>

If i want to initialize just one swiper everything works fine with this code:

var swiper = new Swiper('.swiper-container', {
    pagination: '.swiper-pagination',
    paginationClickable: '.swiper-pagination',
    nextButton: '.swiper-button-next',
    prevButton: '.swiper-button-prev',
    loop: true
});

What i want is to instantiate multiple swipers on one page, like this:

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
    });
});

But this doesn't work for me. I think the propertys are causing problems. Maybe i should do something like this to be more specific and just use to pagination / nextButton / ... inside the current swiper and not on the whole site:

pagination: obj + '.swiper-pagination',
paginationClickable: obj + '.swiper-pagination',
nextButton: obj + '.swiper-button-next',
...

But i don't know exactly how to do it. How can i do this?

回答1:

you need to do something like:

$('.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
    });
});



标签: jquery swiper