按照下面函数的注释中的说明,我尝试选择类'piece的每个成员',将它分成两半(使用:even:odd selectors),然后为它们添加两个不同的类。但是我收到一条错误消息,说每个班级有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.
答案 0 :(得分:1)
setUpPieces函数何时运行?确保在文档准备好之后应用它。您必须添加类的代码看起来正确。这是一个小提琴,展示了它的实际效果:
答案 1 :(得分:0)
你需要使用:nth-child来选择奇数和偶数元素。
$('.piece:nth-child(even)').addClass('light');
$('.piece:nth-child(odd)').addClass('dark');
更新:这是一个有效的演示http://jsfiddle.net/Fy6FC/
答案 2 :(得分: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");
});
}