每隔几秒从数组中的值更改类

时间:2016-04-26 08:53:02

标签: javascript jquery arrays

我试图每3秒更换一次div上的类。类在数组中,应删除前一个类并添加下一个类。 "首先"应该是第一,然后"第二",然后"第三"并回到循环。

我知道如何addClass('something'),但是我被困在代码应该从数组中放入下一个可用类的部分。

<div id="main"></div>

    jQuery(document).ready(function ($) {
    var images = ['first', 'second', 'third'];

    function changeBackground() {
        var className = $('#main').attr('class');
        if (className == null)
            className = images[0];

        $('#main').removeClass(function () {
            var newClass = // find value in array and take next value, if end of array get first
                $(this).addClass(newClass);
        });
    }

    changeBackground();
    setInterval(changeBackground, 2000);
});

https://jsfiddle.net/skd636fc/3/

5 个答案:

答案 0 :(得分:3)

您可以使用计数器来保持类索引的跟踪。

Demo

jQuery(document).ready(function ($) {
    var images = ['first', 'second', 'third'],
        i = 0; // Counter to keep track of the class index

    // Cache the element reference
    var $main = $('#main');

    function changeBackground() {
        $main.attr('class', images[i++]); // Set the class attribute value
        i = i % images.length; // If greater than class length, reset back to 0
    }

    // Add first class on page load
    changeBackground();
    setInterval(changeBackground, 2000);
});

jQuery(document).ready(function ($) {
    var images = ['first', 'second', 'third'],
        i = 0;

    var $main = $('#main');
    function changeBackground() {
        $main.attr('class', images[i++]);
        i = i % images.length;
    }

    changeBackground();
    setInterval(changeBackground, 2000);
});
#main {
    width: 200px;
    height: 200px;
    border: 1px solid red;
}

.first {
    background-color: #f01 !important;
}

.second {
    background-color: blue;
}

.third {
    background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main"></div>

如果可能,将第一个类添加到HTML

中的元素

Demo

<强> HTML:

<div id="main" class="first"></div>

<强> JavaScript的:

jQuery(document).ready(function ($) {
    var images = ['first', 'second', 'third'],
        i = 0;

    var $main = $('#main');
    setInterval(function () {
        $main.attr('class', images[++i % images.length]);
    }, 2000);
});

jQuery(document).ready(function ($) {
    var images = ['first', 'second', 'third'],
        i = 0;
    var $main = $('#main');
    setInterval(function () {
        $main.attr('class', images[++i % images.length]);
    }, 2000);
});
#main {
    width: 200px;
    height: 200px;
    border: 1px solid red;
}

.first {
    background-color: #f01 !important;
}

.second {
    background-color: blue;
}

.third {
    background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main" class="first"></div>

答案 1 :(得分:3)

您无需将函数传递给removeClass。你需要跟踪你所在的课程,这样你就可以在下一个计时器时间点移动到下一个课程。我在评论中解释过:

jQuery(document).ready(function($){   

    var images = ['first', 'second', 'third'];
    // Remember where we are in the array, start just before the first entry
    var classIndex = -1;

    function changeBackground() {

        // Grab the element
        var main = $("#main");

        // If this isn't the first time, remove the previous class
        if (classIndex >= 0) {
            main.removeClass(images[classIndex]);
        }

        // Update the index, wrapping around when we reach the end of the array
        classIndex = (classIndex + 1) % images.length;

        // Add the new class
        main.addClass(images[classIndex]);
    }

    changeBackground();
    setInterval(changeBackground, 2000);

});

关于上述事项的说明:

  • 如果没有解释性评论,它显然会更紧凑
  • 它不会消除#main上其他不相关的类(而使用不带参数的removeClass()的解决方案)

如果你喜欢这种东西,这是一个更紧凑的版本。不过,我不建议将它压缩到这个程度。 : - )

jQuery(document).ready(function($){   
    var classIndex = 0, images = ['first', 'second', 'third'];
    $("#main").addClass(images[classIndex]);
    setInterval(function () {
        $("#main")
            .removeClass(images[classIndex])
            .addClass(images[classIndex = (classIndex + 1) % images.length]);
    }, 2000);
});

答案 2 :(得分:2)

尝试使用counter变量。在setInterval内增加它并使用模数学来创建对数组索引的循环引用,

var images = ['first', 'second', 'third'];
var $elem = $('#main'), cnt = 0;

function changeBackground(){
 $elem.removeClass().addClass(images[cnt++ % images.length]);
}

setInterval((changeBackground(), changeBackground), 2000);

DEMO

答案 3 :(得分:2)

你可以,

var images = ['first', 'second', 'third'];

function changeBackground() {
  var className = $('#main').attr('class');
  var newIndex = (images.indexOf(className) + 1) % images.length;
  $("#main").removeClass().addClass(images[newIndex]);
}
setInterval(changeBackground, 2000);

Fiddle

答案 4 :(得分:2)

&#13;
&#13;
 jQuery(document).ready(function($) {
     var images = ['first', 'second', 'third'],
     	i = 0;

     function changeBackground() {
         $('#main').attr('class', images[i++]);
         i = i % images.length;
     }

     changeBackground();
     setInterval(changeBackground, 2000);
 });
&#13;
#main {
    width: 200px;
    height: 200px;
    border: 1px solid red;
}

.first {
    background-color: #f01 !important;
}

.second {
    background-color: blue;
}

.third {
    background-color: green;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>

<div id="main"></div>
&#13;
&#13;
&#13;