jQuery 延迟添加类/删除类功能不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4954814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:16:13  来源:igfitidea点击:

delayed addclass/remove class function not working

jqueryaddclass

提问by Bizarro Zeldman

what am I doing wroing here?

我在这里做什么?

$(function() {
$('ul li:nth-child(1)').addClass("go").delay(4500).removeClass("go");
$('ul li:nth-child(2)').addClass("go").delay(1500).removeClass("go");
$('ul li:nth-child(3)').addClass("go").delay(500).removeClass("go");
$('ul li:nth-child(4)').addClass("go").delay(4500).removeClass("go");
$('ul li:nth-child(5)').addClass("go").delay(1000).removeClass("go");
});

回答by karim79

Just to add, you can use a .queue:

只是添加,您可以使用.queue

$('ul li:nth-child(1)').addClass("go")
                       .delay(4500)
                       .queue(function() {
                           $(this).removeClass("go");
                           $(this).dequeue();
                       });

回答by David Tang

.delay()is only designed to work with animations. You'll have to resort to using regular setTimeouts for what you're doing:

.delay()仅设计用于动画。您将不得不使用常规的 setTimeouts 来完成您正在做的事情:

var li = $('ul li:nth-child(1)').addClass('go');
setTimeout(function () {
    li.removeClass('go');
}, 4500);

To make doing this to every <li>a little more pleasant, you can refactor your code like so:

为了让每个人都<li>更愉快地执行此操作,您可以像这样重构您的代码:

$(function () {
    var delays = [4500, 1500, 500, 4500, 1000];
    $('ul li').addClass('go').each(function (i) {
        setTimeout(function (li) {
            li.removeClass('go');
        }, delays[i], $(this));
    });
});