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

后端 未结 12 548
南方客
南方客 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:54

    For a table of such a large size I would do the row processing on the server side, using PHP or similar to calculate to odd/even class names for each row. This solution will work for those with JavaScript turned off and will be a lot higher performance than any JavaScript library processing a table element of this size.

    In PHP the logic would look something like

    foreach($rows as $i => $row) {
        $class = ($i % 2 == 0) ? 'even' : 'odd';
    }
    

    If you cannot do any server-side processing I would recommend having the JavaScript set the class tags for each row rather than manipulating the styles directly. This way the presentation is left to the CSS and behaviour is left to the JavaScript and if you do change the way the classes are generated at a later date the presentation code will stay the same.

提交回复
热议问题