0

按照下面函数注释中的说明,我尝试选择“piece”类的每个成员,将其分成两半(使用 :even :odd 选择器),然后向它们添加两个不同的类。但我收到一条错误消息,说每个班级有 0 个成员。我选错了吗?

function setUpPieces() {
    //select all the divs with class 'piece'
    //add the 'light' class to half of them
    //add the 'dark' to the other half
    $('.piece:even').addClass('light');
    $('.piece:odd').addClass('dark');

}

更新:

这些是说明

The jQuery selectors :even and :odd may be useful.

An example:

$('div:even')
selects half of the divs on the page: the first one (the one at index 0) and then every second div after it (the ones at indicies 2,4,6 ...)

$('div:odd')
selects the other half.
4

3 回答 3

1

setUpPieces 函数何时运行?确保在文件准备好后应用它。您必须添加类的代码看起来是正确的。这是一个 Fiddle 显示它的实际操作:

http://jsfiddle.net/DeGeb/

于 2012-09-06T19:08:19.303 回答
0

您需要使用 :nth-child 来选择奇数和偶数元素。

    $('.piece:nth-child(even)').addClass('light');
    $('.piece:nth-child(odd)').addClass('dark');

更新:这是一个工作演示http://jsfiddle.net/Fy6FC/

于 2012-09-06T19:07:06.160 回答
0

您可以遍历所有 .piece 元素,它会更快。

function setUpPieces() {
    //select all the divs with class 'piece'
    //add the 'light' class to half of them
    //add the 'dark' to the other half
    $('.piece').each(function(i) {
        $(this).addClass(i%2 === 0 ? "light" : "dark");
    });
}
于 2012-09-06T19:09:47.607 回答