2010-07-19 67 views
12

今天我注意到jQuery選擇器和addClass()函數的組合在IE8上無法正常工作。IE8和jQuery選擇器

例如,當我想要確保偶數行的表中選擇,我寫道:

jQuery(document).ready(function($){ 
    $("#table1 tr:nth-child(even)").addClass("even"); 
} 

而對於CSS,我寫道:

#table1 tr:nth-child(even), #table1 tr.even { 
    background-color: #ff0; 
} 

在Firefox ,Chrome,Safari和Opera,即使CSS文件中沒有僞類選擇器,也會選擇偶數行。但是,在IE8中,情況並非如此。行沒有不同的背景顏色。

這是奇怪,因爲當我用:

jQuery(document).ready(function($){ 
    $("#table1 tr:nth-child(even)").css({"background-color":"#ff0"}); 
} 

所選行會在IE8突出。


問題的一個例子是問題可以在這裏看到 - 24ways example。在Firefox,Chrome,Safari和Opera中,奇數行被分配了一個「奇數」類。然而,在IE8中,他們沒有被分配一個「奇怪」的類,並沒有突出顯示。

回答

11

選擇器工作正常了jQuery側...但IE8完全丟棄樣式規則(符合the specification),因爲它不承認nth-child

tr:nth-child(odd) td, tr.odd td { 
    background-color: #86B486; 
} 

如果拆分它,它」 LL正常工作:

tr:nth-child(odd) td { 
    background-color: #86B486; 
} 
tr.odd td { 
    background-color: #86B486; 
} 

Here's the original version(單一規則IE8刪除)和here's a fixed sample,隨治分裂。


爲了完整起見,扭轉了規則like this幫助:

tr.odd td, tr:nth-child(odd) td { 
    background-color: #86B486; 
} 
+0

尼克,非常感謝你的修復。它像魔術一樣工作。這確實令人困惑,爲什麼IE8的行爲如此,因爲對於其他僞選擇器它不會發生。例如,當我在jQuery中使用first-child和last-child僞選擇器時,它仍然按預期工作。 再次感謝! – Terry 2010-07-19 14:58:19

+1

@teddyrised - Welcome :)我不確定爲什麼IE的行爲如此,我只是將它添加到它錯誤的50,000件事情列表中。順便說一句,一定要接受答案,關閉問題/幫助下一個傢伙在谷歌上找到這個問題 - 通過左邊的複選標記:) – 2010-07-19 15:00:29

+0

啊,非常感謝您的幫助。儘管我一直潛伏着,但我仍然對堆棧溢出感到陌生。謝謝! – Terry 2010-07-19 15:28:44

2

這對我的作品在IE8和IE9首先需要2類與背景色

.even { background-color: white; } 
.odd { background-color: #ff0; } 

然後用jquery找到tr:odd add tr:even並添加相應的類

$(document).ready(function() { 
     $('#table1').find('tr:odd').addClass("odd"); 
     $('#table1').find('tr:even').addClass("even"); 
});