2012-09-26 58 views
2

我已經創建了這個問題的小提琴,你會看到有三個表使用jQuery的斑馬條。意外的行爲:甚至在jquery中的僞選擇器

表1以正確的形式顯示,因爲它從0開始tr指數爲偶數。表2從最後一個表繼續,它顯示第一行是白色而不是黑色。我認爲這是因爲它正從上表的tr指數繼續。

HTML:

<table> 
    <caption> Table 1</caption> 
    <tr> 
     <th>Table Head 1</th> 
     <td>Table Data 1</td> 
    </tr> 
    <tr> 
     <th>Table Head 2</th> 
     <td>Table Data 2</td> 
    </tr> 
    <tr> 
     <th>Table Head 3</th> 
     <td>Table Data 3</td> 
    </tr> 
</table> 

<table> 
    <caption> Table 2</caption> 
    <tr> 
     <th>Table Head 1</th> 
     <td>Table Data 1</td> 
    </tr> 
    <tr> 
     <th>Table Head 2</th> 
     <td>Table Data 2</td> 
    </tr> 
    <tr> 
     <th>Table Head 3</th> 
     <td>Table Data 3</td> 
    </tr> 
</table> 

<table> 
    <caption> Table 3</caption> 
    <tr> 
     <th>Table Head 1</th> 
     <td>Table Data 1</td> 
    </tr> 
    <tr> 
     <th>Table Head 2</th> 
     <td>Table Data 2</td> 
    </tr> 
    <tr> 
     <th>Table Head 3</th> 
     <td>Table Data 3</td> 
    </tr> 
</table>​ 

的JavaScript:

$('table').find('tr:even').css('background','#d0d0d0'); 

小提琴:http://jsfiddle.net/daljir/gryh5/

回答

1

這是因爲你選擇一般都在TR的(不論表)當他們堆疊時,你會得到這種特殊的行爲。 試試這個:

$('table').find('tr:even').css('background','#d0d0d0'); 

檢查FIDDLE

0

這工作

<table id="t1"> 
    <caption> Table 1</caption> 
    <tr> 
     <th>Table Head 1</th> 
     <td>Table Data 1</td> 
    </tr> 
    <tr> 
     <th>Table Head 2</th> 
     <td>Table Data 2</td> 
    </tr> 
    <tr> 
     <th>Table Head 3</th> 
     <td>Table Data 3</td> 
    </tr> 
</table> 

<table id="t2"> 
    <caption> Table 2</caption> 
    <tr> 
     <th>Table Head 1</th> 
     <td>Table Data 1</td> 
    </tr> 
    <tr> 
     <th>Table Head 2</th> 
     <td>Table Data 2</td> 
    </tr> 
    <tr> 
     <th>Table Head 3</th> 
     <td>Table Data 3</td> 
    </tr> 
</table> 

<table id="t3"> 
    <caption> Table 3</caption> 
    <tr> 
     <th>Table Head 1</th> 
     <td>Table Data 1</td> 
    </tr> 
    <tr> 
     <th>Table Head 2</th> 
     <td>Table Data 2</td> 
    </tr> 
    <tr> 
     <th>Table Head 3</th> 
     <td>Table Data 3</td> 
    </tr> 
</table> 

和JS:

$(function(){ 
    $('#t1 tr:even, #t2 tr:even, #t3 tr:even').css('background','#d0d0d0'); 
}); 

的jsfiddle:http://jsfiddle.net/SnakeEyes/gryh5/2/

4

您選擇文檔中的所有<tr>元素,你可以使用nth-child來選擇器選擇所有偶數<tr> S IN的文件。

$('table tr:nth-child(2n)').css('background','#d0d0d0'); 

http://jsfiddle.net/Kyle_Sevenoaks/gryh5/7/

+1

正相反:http://jsfiddle.net/gryh5/8/。 – VisioN