【问题标题】:.each() is executing without any interval.each() 没有任何间隔地执行
【发布时间】:2013-10-22 01:35:37
【问题描述】:
$(document).ready(function(e) {
    $('.holder').each(function()
    {
        $(this).addClass('dummy');
        setTimeout( function () {
            $('.dummy').children('.box').slideDown('300');
        },2000);
    });
});

我在另一个<div class='holder'> 中有n 个<div>。所以我想给每个孩子<div>添加一些效果。但问题是支架内的所有孩子<div> 同时向下滑动。它似乎不遵守setTimeout()。为什么会这样?

【问题讨论】:

标签: jquery settimeout each


【解决方案1】:

你需要增加循环间隔,还需要在超时回调中使用 hodler 引用

$(document).ready(function (e) {
    $('.holder').each(function (idx) {
        var $this = $(this).addClass('dummy');
        setTimeout(function () {
            $this.children('.box').slideDown('300');
        }, idx * 2000);
    });
});

【讨论】:

  • @Riturajratan 仅供参考,它可以比找到该问题并复制它更快地修复
【解决方案2】:

each 循环几乎立即执行,您为所有setTimeout 调用提供相同的超时。所以它们都是在(即时)循环后 2000 毫秒执行的。

一个简单的解决方案:

$(document).ready(function(e) {
    $('.holder').each(function(i){
        var $this = $(this);
        $this.addClass('dummy');
        setTimeout( function () {
            $('.box', $this).slideDown('300');
        },2000*(i+1)); // give different timeouts
    });
});

【讨论】:

  • 感谢您的解释。但我需要更多帮助。我看到类'dummy'首先被添加到所有持有人<div>,然后发生下滑。所以仍然每个孩子都在同时滑倒。
  • @SuryaS 你的问题不是很清楚,但是编辑后的版本对你有用吗?
  • 谢谢。我写了一个小错字:) 打字能力差:@
【解决方案3】:

使用

$(document).ready(function (e) {
    $('.holder').each(function (interval) { // interval here is index of each loop
        $(this).addClass('dummy');
        var $this = $(this);
        setTimeout(function () {
            $this.children('.box').slideDown('300');
        }, 2000 * (interval + 1));
    });
});

解释

1st timeOut = 2000=  2000 * (interval + 1)=  2000 * (0+ 1)=  2000 * (1)
2nd timeOut = 4000=  2000 * (interval + 1)=  2000 * (1+ 1)=  2000 * (2)
3rd timeOut = 6000=  2000 * (interval + 1)=  2000 * (2+ 1)=  2000 * (3)

等等

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-17
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 2014-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多