delay() not working as expected inside of each() loop (jQuery)

雨燕双飞 提交于 2019-12-01 05:22:15

问题


I have a series of elements that I want to toggle in-and-out of view sequentially. I am using a <button class="toggle"> to control this:

$('.toggle').click(function(){
    $('.squares span').each(function(index){
      $(this).delay(600*index+1).toggleClass('hide');
    });
});

jsFiddle: http://jsfiddle.net/r2vk7L5b/

It appears that the delay() method is simply being ignored in this loop. The index variable is being passed as expected as well. You can console out to see it returning as 0,1,2,3, etc.

What here am I failing to understand about the each() or delay() method?


回答1:


toggleClass isn't one of jQuery's animation (effects) functions (like fadeIn), and delay only works with jQuery's animation functions. toggleClass (and show and hide and several other basic functions) are done immediately, even if there's a delay or other effects pending in the jQuery effects queue.

To simulate delay with a non-animation function, you can use setTimeout:

$('.toggle').click(function(){
    $('.squares span').each(function(index){
      var $this = $(this);
      setTimeout(function() {
          $this.toggleClass('hide');
      }, 600*index+1);
    });
});

Updated Fiddle

Or alternately, consider using an animation (effects) function.



来源:https://stackoverflow.com/questions/30133189/delay-not-working-as-expected-inside-of-each-loop-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!