1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>无标题文档</title> 6 </head> 7 8 <body> 9 <table id="tb1"> 10 <tr><td>1</td></tr> 11 <tr><td>2</td></tr> 12 <tr><td>3</td></tr> 13 <tr><td>4</td></tr> 14 <tr><td>5</td></tr> 15 <tr><td>6</td></tr> 16 <tr><td>7</td></tr> 17 <tr><td>8</td></tr> 18 <tr><td>9</td></tr> 19 <tr><td>10</td></tr> 20 </table> 21 </body> 22 <script type="text/javascript"> 23 window.onload = function(){ 24 var tb1 = document.getElementById("tb1"); 25 var rows = tb1.getElementsByTagName("tr"); 26 for(var i = 0; i < rows.length; i++){ 27 if (i % 2 == 1){ 28 rows[i].style.backgroundColor="#f00"; 29 }else{ 30 rows[i].style.backgroundColor="#0f0"; 31 } 32 } 33 34 //extendChangeColor(3); 35 } 36 37 //隔行变色的扩展,每隔n行进行变色 38 function extendChangeColor(n){ 39 var tb1 = document.getElementById("tb1"); 40 var rows = tb1.getElementsByTagName("tr"); 41 42 for(var i = 0; i < rows.length; i++){ 43 var j = parseInt(i/n);//这里必须取整一下 44 if (j % 2 == 0){ 45 rows[i].style.backgroundColor="#0f0"; 46 }else{ 47 rows[i].style.backgroundColor="#f00"; 48 } 49 } 50 } 51 </script> 52 </html>