【问题标题】:Change class name with variables in loop使用循环中的变量更改类名
【发布时间】:2019-09-16 15:36:35
【问题描述】:

我想根据名称列表(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

【问题讨论】:

  • 在停止函数调用之后,把这个:$text.remove();
  • 我最后的小提琴,感谢 bgaynor78:jsfiddle.net/ary8k30z

标签: javascript jquery loops


【解决方案1】:

所以,我简化了您添加/删除类的方式:


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

【讨论】:

  • 您实际上也不需要$text 元素上的.hide().show()。我已经更新了小提琴和我的答案以反映这一点
  • 我不知道为什么,但这不适用于我正在使用的 jquery 2.1.3。 :S 使用这个 jquery 版本,最后添加的类(在这种情况下是三个)不会被删除。
  • 我明白了,不确定 jquery 中从 v1.7.1 到 2.1.3 的处理方式有何变化,但我能想到的最简单的解决方案是在每个 addClass() 之前清理类列表称呼。我已经更新了答案和要显示的小提琴。基本上,只需在loop函数中添加类之前将类属性更改为$text.attr('class', 'step');的基类即可。
猜你喜欢
  • 2015-10-01
  • 1970-01-01
  • 2021-12-14
  • 2016-06-02
  • 2019-01-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多