javascript - 使用循环中的变量更改类名

标签 javascript jquery loops

我想根据名称列表(var“items”)每 2 秒更改一个类的名称。

我发现了一个相当不错的SO here并尝试将其更改为我的需要。它现在对我有用,但我不知道如何删除 $text 和 div“#div1” - 因为我不需要它。在另一个 SO 中,它用于更改 div 的 html 文本。但我不需要这个,我只想更改该部分的类名 - 我尝试删除此代码,但随后它不再起作用。

HTML:

<section class="steps">class name of this section changes (see inspector)</section>
<div id="div1"></div> <!-- this could be removed -->
<button>Stop it Now.</button>

JS:

$(document).ready(function() {

    var items = ["one", "two", "three"],
        $text = $( '#div1' ),
        $step = $( 'section.steps' ),
        delay = 2; //seconds

    function loop ( delay ) {
        $.each( items, function ( i, elm ){
            $text.delay( delay*1E3).hide();
            $text.queue(function(){
                $text.html( items[i] );
                $text.dequeue(); // this is not needed
                $step.addClass( items[i] ).delay(2000).queue(function(){
                  $(this).removeClass( items[i] ).dequeue();
                });
            });
            $text.show();
            $text.queue(function(){
                if ( i == items.length -1 ) {
                    loop(delay);   
                }
                $text.dequeue();
            });
        });
    }

    loop( delay );

    $("button").on("click", function() {
        $text.stop(true, false);
    })
});

Fiddle

最佳答案

因此,我简化了添加/删除类的方式:


function loop ( delay ) {
        $.each( items, function ( i, elm ){
            $text.delay( delay*1E3);
            $text.queue(function(){
                $text.html( items[i] );
                $text.dequeue(); // this is not needed
                // Sanitize the classlist
                $text.attr('class', 'step');
                // Added these two lines instead of the queue/dequeue
                $text.addClass( items[i]);
            });

            $text.queue(function(){
                if ( i == items.length -1 ) {
                    loop(delay);   
                }
                $text.dequeue();
            });
        });
    }

基本上,我们将采用当前索引并像您一样添加类,但为了删除之前存在的类,我只是返回到以前的索引值。我还更改了 $text var 的值,使其指向您的 step div。

这是更新后的Fiddle

关于javascript - 使用循环中的变量更改类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57960211/

相关文章:

javascript - 查找动态创建元素的前一个同级元素的值

jquery - 如何删除 Jquery Mobile Panel 表单的填充?

java - 尝试在 while 循环内 catch block

php - 我需要帮助来设置 Facebook 应用程序

java - Cloud Endpoint 参数不应命名

javascript - 是否可以从使用 axios 发回 json 响应的端点获取 <options> 的值?

javascript - 单击 jquery 选择中的选项?

javascript - 这些 core-js 包有什么作用? (fix-re-wks, task, iter-define, 等等)

javascript - 动态改变 DOM 中的图像

Mysql,用于全文搜索的存储过程产生部分正确的结果