如何按顺序将class添加到元素集合中? [英] How to add class to a collection of elements sequentially?

查看:70
本文介绍了如何按顺序将class添加到元素集合中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向集合中的每个元素添加一个类.我想将一个类添加到元素中,然后等待一两秒钟,然后将该类添加到集合中的下一个类中.

Im trying to add a class to a each element in a collection. I want add a classs to the elemnt then wait a sec or two then add the class to the next one in the collection.

但是当我使用此代码时,它只是将类一次添加到每个类中.

But when I use this code it just adds the class to each one at once.

for (var i = 0; i < article.length; i++) {
    setTimeout(function () {
        $(article[i]).addClass('something';
        }, 10000);
    }

推荐答案

问题是您要设置从同一时间起10秒的一堆超时,因此它们都将在10秒后立即执行.您需要将它们链接在一起,以便每个超时处理程序调用下一个超时:

The problem is that you are setting a bunch of timeouts 10 seconds from the same moment in time, so they will all execute 10 seconds later at once. You need to chain them together so that each timeout handler invokes the next timeout:

var i = 0;
var callback;

callback = function () {
    if (i < article.length) {
        $(article[i]).addClass('something');

        ++i;
        setTimeout(callback, 10000);
    }
};

setTimeout(callback, 10000);

这篇关于如何按顺序将class添加到元素集合中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆