Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
662 views
in Technique[技术] by (71.8m points)

css - IE8 and jQuery selectors

Today it came to my attention that a combination of jQuery selectors and the addClass() function does not work properly on IE8.

For example, when I want to ensure that even-numbered rows are selected in a table, I wrote:

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

And for the CSS, I wrote:

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

In Firefox, Chrome, Safari and Opera, even without the pseudo-class selector in the CSS file, even-numbered rows are selected. However, in IE8, it is not the case. The rows don't have a different background color.

This is weird because when I used:

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

The selected rows are highlighted in IE8.


An example of the problem is question can be seen here - 24ways example. In Firefox, Chrome, Safari and Opera, the odd rows are assigned an "odd" class. However, in IE8, they are not assigned an "odd" class and are not highlighted.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The selector works correctly on the jQuery side...but IE8 discards the style rule entirely (in compliance with the specification) because it doesn't recognize nth-child:

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

If you split it, it'll work correctly:

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

Here's the original version (a single rule IE8 removes) and here's a fixed sample, with the rule split.


For completeness sake, reversing the rule like this doesn't help:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...