在具有相同索引(i)规则的多个元素上运行.each()

时间:2018-06-19 21:00:30

标签: javascript jquery foreach

我正在开发轮播,逻辑效果很好。但是我注意到我在多个jQuery each()方法中一遍又一遍地重复相同的代码。

function Project(url, defaultColor, subColor){
  this.url = url;
  this.defaultColor = defaultColor;
  this.subColor = subColor;
}
var project1 = new Project("images/preview--1.png", "#9AB999", "#C5DEC4");
var project2 = new Project("images/preview--2.png", "#EC7F7A", "#FFB3AF");
var project3 = new Project("images/preview--3.png", "#E4475C", "#C45C6A");
var project4 = new Project("images/preview--4.png", "#00999E", "#35CFD4");
var project5 = new Project("images/preview--5.png", "#355D7D", "6DA2CC");
var project6 = new Project("images/preview--6.png", "#283338", "#638B9E");
var project7 = new Project("images/preview--7.png", "#CDE377", "#AAB67A");
var projects = [project1, project2, project3, project4, project5, project6, project7];


var imageSource = $('.image-wrapper picture source'),
content = $('.carousel__content'),
circle1 = $('.expand-1st'),
circle2 = $('.expand-2nd');
var scrollPosition = 0;


function loadNextProject(){
  scrollPosition = scrollPosition + 1;
  if(scrollPosition === projects.length){
    scrollPosition = 0;
  }

  imageSource.each(function(i, elem) {
    var num = i + scrollPosition;
    if(num >= projects.length){ num = i + scrollPosition - projects.length;}
    var x = projects[num];
    var url = x.url;

    $(this).attr('srcset', url);
  });
  content.each(function(i, elem){
    var num = i + scrollPosition;
    if(num >= projects.length){ num = i + scrollPosition - projects.length;}
    var x = projects[num];
    var backgroundColor = x.defaultColor;
    // console.log(x)

    $(this).css({'background' : '' + backgroundColor + ''});
  });
  circle1.children('circle').each(function(i, elem){
    var num = i + scrollPosition;
    if(num >= projects.length){ num = i + scrollPosition - projects.length;}
    var x = projects[num];
    var backgroundColor = x.defaultColor;
    // console.log(x)

    $(this).css({'fill' : '' + backgroundColor + ''});
  });

  console.log(scrollPosition)
}

我想知道是否有一种方法可以循环遍历所有已分配的元素imageSourcecontentcircle1,并使用具有相同索引{{1 }}:

i

以上代码每个均重复了三个。我们能只用一个each()实现电流吗?

1 个答案:

答案 0 :(得分:0)

我正在使用具有如下相关参数的函数进行工作,并且可以正常工作。只是不确定这是否是最好的方法。任何建议都请纠正我:)

function loadAll(element){
    element.each(function(i){
      var num = i + scrollPosition;
      if(num >= projects.length){ num = i + scrollPosition - projects.length;}
      var x = projects[num];

      var url = x.url,
      backgroundColor = x.defaultColor;
      //
      // console.log(element)

      if(element == imageSource){
        $(this).attr('srcset', url);
      }else if(element == content){
        $(this).css({'background' : '' + backgroundColor + ''});
      }else if(element == circle1){
        $(this).css({'fill' : '' + backgroundColor + ''});
        console.log('run this')
      }else{
        return;
      }

    });
  }
  loadAll(imageSource);
  loadAll(content);
  loadAll(circle1);