javascript - Loop within a function to alt color table rows -
i have query building form built in php. results of query returned , placed in 2 different tables 1 above other. (table id's results, , results2) each record returned builds 2 tables display data. (soon three)
i'm using following code change class tags of <tr>'s provide alternate row coloring:
<script type="text/javascript"> function alternate(id){   if(document.getelementsbytagname){     var table = document.getelementbyid(id);     var rows = table.getelementsbytagname("tr");     for(i = 0; < rows.length; i++){       if(i % 2 == 0){        rows[i].classname = "row-one";        }else{        rows[i].classname = "row-two";             }           }          }         } </script>   then i'm using body onload so:
<body onload="alternate('results'); alternate('results2');">   the problem colors first 2 instances of these tables, when depending on amount of records returned there hundreds of them.
how can function apply every table in document id = results , results2 , results3?
if really want javascript, suggest following code:
first, make tables have class of "results" instead of id "results1", "results2", etc (because comment on question says, ids must unique, , getelementbyid return 1 result , apply 1 real element):
<table class="results">...</table>   next, use javascript:
<script type="text/javascript"> function alternate(classnamematch) {     var tables = document.getelementsbytagname("table");     (var i=0; < tables.length; i++) {         var table = tables[i];         if (table.classname.indexof(classnamematch) == -1)) continue;          (var j=0; j < table.rows.length; j++) { // "table" elements have "rows" collection built-in             table.rows[j].classname = j % 2 == 0 ? "row-one" : "row-two";         }     } } </script>   then call alternate("results"); on page load.
but, really suggest doing in php. javascript very inefficient large result sets. not show right away, making style of page visibily change after page load.
i add class every other row, , style rows default 1 way , other class other way:
<style type="text/css"> table.results tr { background-color:#f0f0f0; } table.results tr.row2 { background-color:#f0f0ff; } </style>      
Comments
Post a Comment