2017-04-19 65 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