delayed addclass/remove class function not working

后端 未结 2 939
清歌不尽
清歌不尽 2020-12-02 23:52

what am I doing wroing here?

$(function() {
$(\'ul li:nth-child(1)\').addClass(\"go\").delay(4500).removeClass(\"go\");
$(\'ul li:nth-child(2)\').addClass(\"         


        
相关标签:
2条回答
  • 2020-12-03 00:31

    Just to add, you can use a .queue:

    $('ul li:nth-child(1)').addClass("go")
                           .delay(4500)
                           .queue(function() {
                               $(this).removeClass("go");
                               $(this).dequeue();
                           });
    
    0 讨论(0)
  • 2020-12-03 00:51

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

    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:

    $(function () {
        var delays = [4500, 1500, 500, 4500, 1000];
        $('ul li').addClass('go').each(function (i) {
            setTimeout(function (li) {
                li.removeClass('go');
            }, delays[i], $(this));
        });
    });
    
    0 讨论(0)
提交回复
热议问题