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

Obviously, the actual style of the odd / even lines will be done using the CSS class, but what is the best way to “attach” the class to the lines? Is it better to put it in the markup, or is it better to do it through client-side javascript? Which is better and why?

For simplicity, suppose this is a large table with 100 rows and that the color scheme alternates with odd / even rows. In addition, some javascript library that can easily do this is needed elsewhere on the page, and therefore the overhead of this package is not a factor.


The real purpose of this question is to determine which trade-offs are involved, as well as how these trade-offs should be handled, for example, when achieving performance on the server, if the page is under load (suppose a dynamic table), bandwidth for users with more low connection speed, semantic punches by adding additional layout code to HTML (the idea here is that HTML is for content, CSS is for layout, and javascript is for how content behaves t, and also controls / supplements the layout)

+2
source share
12 answers

You can do this quite easily with jQuery, for example:

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

, , "li".

, , ,

+11

( ). . rowNum = (rowNum - 1) * -1 , , - , javascript.

+6

, , , , javascript.

JS-, jQuery, , :

$(document).ready(function() {
  $('.myTable tr:odd').addClass('alternateRow');
});
+2

, PHP / . , JavaScript , , JavaScript, .

PHP

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

, , JavaScript , . , CSS, JavaScript, , .

+1

, javascript. / javascript, /. , , Javascript, (, , , ).

+1

-, CSS. , CSS 2001, - . = (

+1

, , CSS3:

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

w3 css3. , javascript .

+1

. JavaScript , " ". , , "row_alternate". , , JavaScript.

0

- , , , , .

Else googled "jscript table alternating colors" .

( : , .)

0

, / , , .

0

, , . , , .

, script / . , 100 , onload, , . , . , , , .

0
source

All Articles