2016-08-03 74 views
6

我試圖寫這個函數,它將從#rc中獲取用戶輸入並創建一個這樣大小的棋盤。問題tr:奇數jquery

它工作正常,當n是一個偶數如8,但如果n是一個奇數,如9,每個「tr:2n + 1」是錯誤的。這是什麼原因?我該怎麼處理它?先謝謝你!

function setUpCheckBoard() 
{ 
    var n = $("#rc").val(); 
    var stn= Number(n)+1; 
var col = new Array(stn).join('<td></td>'); 
    var row = new Array(stn).join('<tr>' + col + '</tr>'); 

$('tbody').append(row); 
    $("tr:odd td:odd").css("background-color", "black"); 
$("tr:odd td:even").css("background-color", "white"); 
$("tr:even td:odd").css("background-color", "white"); 
$("tr:even td:even").css("background-color", "black"); 
} 

回答

3

你想這樣的:

$("tr:odd td:nth-child(2n+1)").css("background-color", "black"); 
$("tr:odd td:nth-child(2n)").css("background-color", "white"); 
$("tr:even td:nth-child(2n+1)").css("background-color", "white"); 
$("tr:even td:nth-child(2n)").css("background-color", "black"); 

:odd:even選擇不關心所選擇的元素的父/子關係;他們從所有匹配元素中選擇其他所有元素

因此,你需要tr:odd td,並從表格的各行中獲取一堆td元素。當你做那些時,jQuery只是通過其他所有匹配td - 其中一些將在第一列,其中一些將在第二列。

使用:nth-child(2n):nth-child(2n+1)根據它們在父行中的位置來選擇元素。

+0

太謝謝你了! ! – SammiA

1

或者您可能希望普通的老CSS來爲您處理它,就像這樣:

<style type="text/css"> 

    /* WHITE DEFAULT COLOUR */ 
    table tr td { 
     background-color:white; 
    } 

    /* BLACK OVERRIDE COLOUR */ 
    table tr:nth-child(even) td:nth-child(even), table tr:nth-child(odd) td:nth-child(odd) { 
     background-color:black; 
    } 

</style> 
+0

謝謝!我決定改用css。哈哈謝謝。 – SammiA

+0

很高興幫助! :) – Ren