简体   繁体   English

使用each()循环div

[英]loop divs using each()

I've been struggling with the following: A set of 5 classes needs to change colour one after another with an interval of 2 seconds. 我一直在努力解决以下问题:一组5个类需要以2秒为间隔一次又一次地更改颜色。 Now I know I have to make use of .each() however I cannot find anywhere how to properly loop through my divs. 现在我知道我必须使用.each(),但是我找不到任何地方可以正确循环遍历我的div。 They all have the class circle as shown below: 他们都有班级圈子,如下所示:

        <div data-text="I've" id="circle1" class="circle">
            <h1>  </h1>
        </div>

        <div data-text="got" id="circle2" class="circle">
            <h1>  </h1>
        </div>

        <div data-text="some" id="circle3" class="circle">
            <h1>  </h1>
        </div>

        <div data-text="stuff" id="circle4" class="circle">
            <h1>  </h1>
        </div>

        <div data-text="toDo" id="circle5" class="circle">
            <h1>  </h1>
        </div>

So I've got the interval, which wasn't a real problem. 所以我有了间隔,这不是一个真正的问题。 However now I'm stuck at getting the loop to work: 但是现在我被困在使循环起作用:

var circle = $(".circle");



circle.each(function(){

setInterval(function(){ 
 $('.circle').toggleClass('yellow');  
    setTimeout(function(){
    $('.circle').toggleClass('yellow');  
 },2000)
 },4000);
 });

I would really appreciate some help on this. 我真的很感谢这方面的帮助。 My thanks in advance! 预先感谢!

I don't think you really need to use the setInterval as in your scenario, but if you really want to / need to use it, I would suggest you find a way to clear your intervals at the end. 我不认为您确实需要像在方案中那样使用setInterval ,但是如果您确实想要/需要使用它,我建议您找到一种在最后清除间隔的方法。

A way you could do it with a simple setTimeout would be like this 您可以使用简单的setTimeout做到的方式是这样的

 function doColoring(targetClass) { runThroughSamples( Array.prototype.slice.call($(targetClass)), 500, 'yellow' ); } function runThroughSamples( samplesArr, timeout, classToToggle ) { if ( !samplesArr || !samplesArr.length ) { return; } setTimeout( function() { $(samplesArr[0]).toggleClass(classToToggle); runThroughSamples( samplesArr.slice(1), timeout, classToToggle ); }, timeout); } 
 .yellow { background-color: yellow; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="item"> 1 </div> <div class="item"> 2 </div> <div class="item"> 3 </div> <div class="item"> 4 </div> <div class="item"> 5 </div> <button type="button" onclick="doColoring('.item')">Start setTimeout example</button> 

ofcourse you could do it with an interval as well, just it would be important to clear the interval afterwards 当然,您也可以使用一个间隔来完成此操作,只是在之后清除间隔很重要

 function doColoring(targetClass) { runThroughSamples( Array.prototype.slice.call($(targetClass)), 500, 'yellow' ); } function runThroughSamples( samplesArr, timeout, classToToggle ) { if ( !samplesArr || !samplesArr.length ) { return; } var interval = setInterval( function() { $(samplesArr[0]).toggleClass(classToToggle); samplesArr.splice(0, 1); if (samplesArr.length === 0) { clearInterval(interval); } }, timeout); } 
 .yellow { background-color: yellow; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="item"> 1 </div> <div class="item"> 2 </div> <div class="item"> 3 </div> <div class="item"> 4 </div> <div class="item"> 5 </div> <button type="button" onclick="doColoring('.item')">Start setInterval example</button> 

This is what you have to do. 这就是你要做的。 Demo Working Fiddle 演示工作小提琴

  1. First set a start point for the interval to start at. 首先设置间隔的起点。 Lets make the first circle as the start $('#circle1') 让我们将第一个圆圈作为开始$('#circle1')

  2. Then use the Jquery setInterval to run at every 2 secs (2000 ms). 然后使用Jquery setInterval2秒(2000毫秒)运行一次。

  3. append the class yellow inside the interval, And update the pointer to point to next element. 在间隔内添加yellow类,并更新指针以指向下一个元素。

Jquery code is as below. jQuery代码如下。

var circle = $('#circle1'); //start element

setInterval(function(){ 
      $('.yellow').removeClass('yellow');  //remove existing classes
      circle.addClass('yellow');           // add the class to current circle
      circle = circle.next();              //point the circle to next element. 

  if(circle.length === 0){         //if we have reached the last element go back to top
   circle = $('#circle1');
  }
}, 2000);

Inside "each" function, you don't have to again parse document for ".circle" class. 在“每个”函数中,您不必再次为“ .circle”类解析文档。 You are basically setting the class "yellow" to ALL the divs and then resetting it back to ALL. 您基本上是将类“ y​​ellow”设置为所有div,然后将其重置为ALL。

You should use "this" or pass iterator parameter to function and use that to toggle class. 您应该使用“ this”或传递迭代器参数来起作用并使用它来切换类。

To iterate over an array of elements. 遍历元素数组。

var circles = $('.circle');
circles.each(function(index, item) {
   var $item = $(item);
   // Do your stuff with your item.
});

You need to decorate the item with a $ to make it a full jQuery element. 您需要使用$装饰项目以使其成为完整的jQuery元素。

But what you only need is to have an interval and to track the state of your divs, tracking which div was the last having the yellow class, to set the next one. 但是,您只需要有一个间隔并跟踪div的状态,跟踪哪个div是具有黄色类的最后一个div,以设置下一个。 It can be done with a single interval. 可以以单个间隔完成。

var circles, yellowCircleIndex,
changeColors;

circles = $('.circle');
yellowCircleIndex = circles.length;

changeColors = function() {
    var previousDiv, currentDiv;
    previousDiv = circles.eq(yellowCircleIndex);
    yellowCircleIndex = (yellowCircleIndex + 1) % circles.length;
    previousDiv.removeClass('yellow');
    currentDiv = circles.eq(yellowCircleIndex);
    currentDiv.addClass('yellow');
};

changeColors();
setInterval(changeColors, 2000);

It's more efficient to have a single interval than one for each div. 与每个div一个间隔相比,有一个间隔更有效。 As far as I understood, you want a single div with the yellow class at a time, right? 据我了解,您希望一次将一个div包含一个黄色类,对吗?

I hope i understood your desired outcome, you have a problem with your syntax both in the jQuery each and the setTimeout and setInterval. 我希望我理解了您想要的结果,jQuery和setTimeout和setInterval中的语法都有问题。

Plus i think this is more of a recursion solution than a loop one, i did the following function: 另外,我认为这比循环解决方案更像是一种递归解决方案,我做了以下功能:

var circles = $(".circle");
var counter = 0;

function paintInYellow(div) {
  setTimeout(function() {
    div.toggleClass('yellow');
    if (counter < circles.length) {
      counter++;
    } else {
      counter = 0;
    }
    paintInYellow(circles.eq(counter));

  }, 2000);
}
paintInYellow(circles.first());

you can see a working example on a fiddle i did, here - https://jsfiddle.net/fistuks/rL1h51fv/ 您可以在这里看到一个小提琴上的工作示例-https: //jsfiddle.net/fistuks/rL1h51fv/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM