开发者

How do I sort my table and keep alternating background colors while sorting using jquery?

I am having a problem wi开发者_StackOverflow社区th my table rows background colors once I start sorting columns. When my document loads the code is runs like this:

$('tbody tr:even').css('background-color','#F1F1F1');
$('tbody tr:odd').css('background-color','#FFFFF0');

The code to sort my th is this:

$('.toggle').toggle(function(){
    $(this).css("background-image", "url('desc.gif')");
}, function(){
    $(this).css("background-image", "url('asc.gif')");
});

but once they start sorting there are even rows right on top of each other and odd rows on top of each other. What can I right to alternate row color when sorting? I have already tried the following and it does not work:

$('.toggle').toggle(function(){
   $(this).css("background-image", "url('desc.gif')");
   $('tbody tr:even').css('background-color','#F1F1F1');
   $('tbody tr:odd').css('background-color','#FFFFF0');
 }, function(){
   $(this).css("background-image", "url('asc.gif')");
   $('tbody tr:even').css('background-color','#F1F1F1');
   $('tbody tr:odd').css('background-color','#FFFFF0');                 
 });


You can get sorting and zebra striping out-of-the-box if you just use jQuery Tablesorter. I use it all the time, it works great.

An example of a table set up with sorting that maintains the proper alternating row colours would be:

$("#mytable").tablesorter({
  widgets: ['zebra']
});


Whenever anyone is dealing with table sorting, paging, etc I immediately refer them to DataTables. It does this sort of sorting properly while maintaining the "zebra stripe" layout you're looking for. I have it working currently in my company's app and it's great.

The reason I always suggest this approach is for the extra features you get. Sorting, Paging, Filtering, and results limiting, all via a table loaded to the dom or via JSON or AJAX datasources. Plus, add in ThemeBuilder for quick styling and outstanding, well supported CSS and it makes a tool that can't be ignored.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜