2010-07-19 50 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"); 
});