1

我正在使用该setInterval()方法尝试将一个类应用于每个人li

我创建了一个应用 toggleClass 的 jsFiddle,但我无法让它一一应用该类。

下面是我的 javaScript,我还添加了 jsFiddle 的链接:

var i = 1;
var id = setInterval(function () {
    $("ul").children(i).toggleClass('test');
    i++;
    if (i === 4) {
        i = 1;
    }
}, 1000);

http://jsfiddle.net/Svx3n/42/

4

4 回答 4

1

Two issues that I spot:

When working with indexes, the index starts at zero, not one.

.children(\[selector\]) does not take an index, it takes a selector. So you are asking jQuery to find the element of type of one. Instead use .eq(index) to get the element.

So the changes to your code would be:

var i = 0;
var id = setInterval(function () {

    $("ul").children().eq(i).toggleClass('test');

    i++;

    if (i === 4) {
        i = 0;
    }

}, 1000);

Better yet, move the selecting out so you are not doing the querying of the DOM every iteration

var i = 0,
    lis = $("ul").children(),
    id = window.setInterval( function () {    
            lis.eq(i).toggleClass('test');    
            i++;    
            if (i === 4) {
                i = 0;
            }    
         }, 1000);
于 2013-08-29T12:54:10.480 回答
0

Demo

var i = 0;
    var id = setInterval(function () {

        $("ul li").eq(i).toggleClass('test');
        i++;
        if (i === 4) {
            i = 0;
        }

    }, 1000);
于 2013-08-29T12:53:42.687 回答
0

Try

var i = 0, $lis = $("ul li");
var id = setInterval(function () {
    $lis.eq(i).toggleClass('test');
    i++;

    i = i % $lis.length;
}, 1000);

Demo: Fiddle

于 2013-08-29T12:55:02.233 回答
0

您需要将 ":nth-child" 与 "i" 一起使用

于 2013-08-29T12:51:58.160 回答