What is the best way to style alternating rows in a table?

后端 未结 12 507
南方客
南方客 2020-12-11 11:09

Obviously, the actual style of the odd/even rows will be done via a CSS class, but what is the best way to \"attach\" the class to the rows? Is is better to put it in the ma

相关标签:
12条回答
  • 2020-12-11 11:37

    You can do this fairly easily with jQuery, like so:

    $(function(){
        $('tr:even').addClass('alternateClass');
        $('tr:odd').addClass('mainClass');
    });
    

    You can qualify the selector a bit more if you just want to do this on one particular table, or do it on 'li' elements as well.

    I think this is a bit cleaner and more readable client-side than it would be in some server-side environments,

    0 讨论(0)
  • 2020-12-11 11:38

    I found a good site explaining what you want to achieve using jquery:

    Here is the final output- http://15daysofjquery.com/examples/zebra/code/demoFinal.php

    And here is the tutorial- http://15daysofjquery.com/examples/zebra/

    0 讨论(0)
  • 2020-12-11 11:39

    I would say really that it depends on the situation. If you are looping through the data to create the rows on the server side, I would probably say that you should do it there.

    This gets a lot more complicated if you are going to start using client side script to sort/reorder the rows. In this case if it's 100 rows or so I might be inclined to do it on the onload event client side, because at least that way you aren't duplicating code to determine the row color. I'll admit, it really depends on the speed of it in this case. I would probably try it and see if the performance is acceptable before making a final decision.

    0 讨论(0)
  • 2020-12-11 11:40

    It depends on your scenario. JavaScript based may be quicker to implement for a number of rows if the table is not being created on-the-fly. If you're dynamically creating your table, however, you could pretty easily set the class for every other row to be "row_alternate" -- I prefer the server side method if you are concerned that some of your users may not have JavaScript.

    0 讨论(0)
  • 2020-12-11 11:41

    I always apply the class on the server side as they are streamed out/added to the page, but if you have a client-side re-sorting the rows will need to be re-classed.

    0 讨论(0)
  • 2020-12-11 11:42

    What you're trying to accomplished can even be done with CSS3:

    tr:nth-child(odd) { background: #FFF; }
    tr:nth-child(even) { background: #AAA; }
    

    This is also listed in the w3's css3 selectors spec. If you're looking for compatibility, adding the class server-side or through javascript would be a far better solution.

    0 讨论(0)
提交回复
热议问题