2017-04-19 61 views
0

我想下面的轉換成一個更優雅的解決方案,可能是一個循環來追加數組給Swiper.js的子彈:嘗試使用循環

jQuery(document).ready(function() { 
var swiper = new Swiper('.swiper-container', { 
    pagination: '.swiper-pagination', 
    paginationClickable: true, 
    paginationBulletRender: function (swiper, index, className) { 
     var index; 
     var a = ['Item One', 'Item Two', 'Item Three', 'Item Four', 'Item Five']; 
     if (index === 0) { 
      return '<span class="' + className + '">' + (a[0]) + '</span>'; 
     } 
     if (index === 1) { 
      return '<span class="' + className + '">' + (a[1]) + '</span>'; 
     } 
     if (index === 2) { 
      return '<span class="' + className + '">' + (a[2]) + '</span>'; 
     } 
     if (index === 3) { 
      return '<span class="' + className + '">' + (a[3]) + '</span>'; 
     } 
     if (index === 4) { 
      return '<span class="' + className + '">' + (a[4]) + '</span>'; 
     } 
     if (index === 5) { 
      return '<span class="' + className + '">' + (a[5]) + '</span>'; 
     } 
    } 
}); 

}); 

我曾嘗試過各種循環技術,如雞舍this SO post,尤其是這一個:

var index; 
var a = ["a", "b", "c"]; 
for (index = 0; index < a.length; ++index) { 
    console.log(a[index]); 
} 

創建以此爲循環:

jQuery(document).ready(function() { 
    var swiper = new Swiper('.swiper-container', { 
     pagination: '.swiper-pagination', 
     paginationClickable: true, 
     paginationBulletRender: function (swiper, index, className) { 
      var index; 
      var a = ['Item One', 'Item Two', 'Item Three', 'Item Four', 'Item Five']; 
      for (index = 0; index < a.length; ++index) { 
       return '<span class="' + className + '">' + (a[index]) + '</span>'; 
      } 
     } 
    }); 

});

但這只是顯示每個項目符號數組中的第一項。我創建了一個JS Fiddle here

這只是一個原型,所以陣列不會改變,請有人可以幫忙嗎?

謝謝!

回答

0

組隊,探索本身重複五次,你不需要爲循環再次,反覆檢查解決方案>>https://jsfiddle.net/nv0mfy0z/1/

var a = ['Item One', 'Item Two', 'Item Three', 'Item Four', 'Item Five']; 

paginationBulletRender: function (swiper, index, className) { 
     return '<span class="' + className + '">' + (a[index]) + '</span>';    
    } 
+0

好極了!謝謝 :) – user3327812