0

以下の関数のコメントの指示に従って、クラス 'piece' のすべてのメンバーを選択し、(:even :odd セレクターを使用して) 半分に分割し、2 つの異なるクラスをそれらに追加しようとしました。しかし、各クラスのメンバーが 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 に答える