当存在多个滑块实例时,调用下一个前一个iDangero.us

时间:2013-09-13 14:28:21

标签: javascript jquery

我正在使用idangero.us滑块。我的页面上有多个滑块。我需要在滑块上添加下一个/上一个按钮。这是我目前的实施。以下问题是点击事件会调用页面上的所有滑块。当存在多个实例时,使用swipePrev和swipeNext函数的最佳方法是什么。

    $('.swiper-container').each(function () {

    var prevNext = "<a class='arrow-left' href='#'></a><a class='arrow-right' href='#'></a>"; 
    var config = {
      mode: 'horizontal',
      calculateHeight: true,
      initialSlide: 0,
      visibilityFullFit: true
    };

    if ($(this).find('.swiper-wrapper').children().length > 1) {
      $(this).prepend(prevNext);
      var $pager = $('<div class="pagination" />').appendTo(this);
      config.pagination = $pager[0];
      config.paginationClickable = true;
    }

    var swiper = $(this).swiper(config);

    $('.arrow-left').on('click', function (e) {
        e.preventDefault();
        swiper.swipePrev();
    });

    $('.arrow-right').on('click', function (e) {
        e.preventDefault();
        swiper.swipeNext();
    });

  });

2 个答案:

答案 0 :(得分:2)

像这样创建多个块的实例

<div class="device">
<a class="arrow-left" href="#"></a> 
<a class="arrow-right" href="#"></a>
<div class="swiper-container">
  <div class="swiper-wrapper">
    <div class="swiper-slide"> <img src="img/slider1-1.png"> </div>
    <div class="swiper-slide"> <img src="img/slider1-2.png"> </div>
  </div>
</div>
<div class="pagination"></div>
</div>

并将此js与objects数组和漂亮的find()选择器一起使用。

var swipes = []
$('.swiper-container').each(function(i, obj) {
swipes[i] = new Swiper(obj);

$(this).parent().find('.arrow-left').on('click', function(e){
  e.preventDefault()
  swipes[i].swipePrev()

})    

$(this).parent().find('.arrow-right').on('click', function(e){
  e.preventDefault()
  swipes[i].swipeNext()    
})  


});

答案 1 :(得分:1)

这应该有效:

    var swiper = [];

    $('.swiper-container').each(function(index){

        var $el = $(this);

        swiper[index] = $el.swiper({
            //Your options here:
            mode:'horizontal',
            pagination: $el.find('.swiper-pagination')[0],
            ... more settings here
        });

        $el.find('.prev-slide').on('click', function(){
            swiper[index].swipePrev();
        });

        $el.find('.next-slide').on('click', function(){
            swiper[index].swipeNext();
        });

    });