问题
Using jQuery and not CSS, is it possible to alternate row colors between records? If so can anyone provide a short code script on how to accomplish this?
回答1:
Try this:
$("tr:even").css("background-color", "#eeeeee");
$("tr:odd").css("background-color", "#ffffff");
回答2:
Do you just not want to use CSS for cross-browser (i.e., IE) support? If so, you could keep the styling in the CSS and just use jQuery to set the class.
For example:
<style>
/* tr:nth-child(even) */
tr.even { background-color: white; }
/* tr:nth-child(odd) */
tr.odd { background-color: black; }
</style>
<script>
$(function(){
// Apply to each table individually and make sure nothing is doubleclassed
// if you run this multiples of times.
$('table').each(function() {
$('tr:odd', this).addClass('odd').removeClass('even');
$('tr:even', this).addClass('even').removeClass('odd');
});
});
</script>
回答3:
You can select tr
elements from a table and css accepts a function as a parameter, which will return a value based on some criteria you decide. In this case, you can test the index for evenness.
$("#table tr").css("background-color", function(index) {
return index%2==0?"blue":"red";
});
JSFiddle: http://jsfiddle.net/n3Zny/
回答4:
jQuery uses the Sizzle Seletor Engine, which is cool because it uses the same syntax as CSS. So you use the same selector as CSS but then use the jQuery .css()
function to alter the elemen't CSS:
$('#table_id').find('tr:even').css({'background-color':'red'})
.end().find('tr:odd').css({'background-color':'blue'});
This code example selects the table you want to alter, then selects all the even child elements (tr
's) and changes their background color, it then uses .end()
to return to the previous selection of the entire table and selects the odd rows to alter their CSS.
回答5:
I used following code to change color of alternate row. I have taken reference from http://www.tutsway.com/set-alternate-row-colors-in-jQuery.php
window.jQuery(document).ready(function(){
window.jQuery("tr:odd" ).css("background-color","#fbcff5" );
window.jQuery("tr:even").css("background-color","#bbbbff");
});
回答6:
For anyone wanting to skip over hidden rows (or another attribute, say class="struck"
):
<style>
tr.struck{background-color:#633;color:white;}
tr.eee{background-color:#EEE;color:#000;}
tr.fff{background-color:#FFF;color:#000;}
</style>
function doZebra(){
var tTrCnt=0;
$("##tblData tbody tr").each(function(){
if($(this).css("display")!="none" && !$(this).hasClass("struck")){
tTrCnt++;
if(tTrCnt % 2) $(this).removeClass().addClass("eee");
else $(this).removeClass().addClass("fff");
}
});
}
来源:https://stackoverflow.com/questions/8128581/alternate-row-colors-using-jquery