本文介绍了delay()在each()循环内无法按预期工作(jQuery)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列元素,我想按顺序在视图内外切换.我正在使用<button class="toggle">来控制它:

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/

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

在此循环中,似乎只是忽略了delay()方法. index变量也按预期方式传递.您可以退出控制台,以返回0、1、2、3等.

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.

我对each()delay()方法不了解什么?

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

推荐答案

toggleClass不是jQuery的动画(效果)功能(如fadeIn),而delay仅适用于jQuery的动画功能. toggleClass(以及showhide以及其他几个基本功能)可以立即完成,即使jQuery效果队列中有延迟或其他效果待处理.

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.

要使用非动画功能模拟delay,可以使用setTimeout:

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);
    });
});

更新了小提琴

或者,考虑使用动画(效果)功能.

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

这篇关于delay()在each()循环内无法按预期工作(jQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 03:30