开发者

JQuery using each() as classic for each loop and not all at once

开发者 https://www.devze.com 2023-02-04 11:20 出处:网络
I\'m trying to loop through a set of div tags and fade them in and out one at a time. So far, using the .each() operator, it does them all at once.

I'm trying to loop through a set of div tags and fade them in and out one at a time. So far, using the .each() operator, it does them all at once. How do you use .each() as a more classic for each loop?

Here is my JQuery code snippet and currently it fade all the div tags in and out together not one by one.

$("document").ready(function() {   
// all div tags are hidden at start 

    $(".myclass").each(function (i) {
      var $div = $(this);
      showDiv($div);
      hideDiv($div);
});

function showDiv(theDiv)
{
      $(theDiv).fadeIn(4000);
}

function hideDiv(theDiv)
{
       $(theDiv).fadeOu开发者_如何学JAVAt(4000);
}     
});

thank you for considering the question,


It's not about using .each() versus a plain for loop. The problem is that the animations are handled via timeouts (managed by jQuery). Calls to .fadeIn() and .fadeOut() return immediately, before the animations have taken place.

You could add some delay to each fadeIn(), or you could structure your code differently:

$("document").ready(function() {   
  var divs = $('.myclass'), i = 0;
  function reveal() {
    if (i === divs.length) return;
    divs.eq(i).fadeIn(4000, function() {
      divs.eq(i).fadeOut(4000, function() {
        i++;
        setTimeout(reveal, 0);
      });
    });
  }
  setTimeout(reveal, 0);
});


Use delay:

var delay = 0;
$(".myclass").each(function (i) {
    var $div = $(this);
    showDiv($div);
    hideDiv($div, delay);
    delay += 100;
});


function hideDiv(theDiv, delay)
{
    $(theDiv).fadeOut(4000).delay(delay);
}   


Your .each function works as expected. What doesn't work as expected is the fact that Javascript is asynchronous in nature. It doesn't wait for showDiv to complete before calling hideDiv again. The calls then start to conflict with each other.

What you want to use instead is an interval which isn't actually a part of jQuery itself but build into Javascript.

Something like this:

function showHide(theDiv) {
     if( $(theDiv).is(":visible") ) {
          $(theDiv).fadeOut(4000);
     }
     else {
          $(theDiv).fadeIn(4000);
     }
}

setInterval( function() { showHide("#theDivsID") }, 4100 );
0

精彩评论

暂无评论...
验证码 换一张
取 消