利用JS动态生成隔行换色HTML表格的两种方法
网络 2018-11-06 1250
用JS生成动态生成表格,行、列由用户输入,并使表格隔行换色
方法一.
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | <!DOCTYPE html> <html> <head> <title>动态表格</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css" rel="external nofollow" rel="external nofollow" >--> <script type="text/javascript"> function createTable(){ var table = document.createElement("table"); //添加边框 table.border = "1"; table.width = "100%"; //table API //创建一行 //var tr = table.insertRow(table.rows.length); //创建单元格 //var td = tr.insertCell(tr.cells.length); //行,单元格 var tr,td; //获得行列值 var tr_value = document.getElementById("tr_value").value; var td_value = document.getElementById("td_value").value; for(var i=0;i<tr_value;i++){ //循环插入元素 tr = table.insertRow(table.rows.length); if(i%2 === 0){ tr.style.backgroundColor = "#D5E3D0"; }else{ tr.style.backgroundColor = "#909C97"; } for(var j=0;j<td_value;j++){ td = tr.insertCell(tr.cells.length); td.innerHTML = "_"; td.align = "center"; } } //td.innerHTML = "测试"; document.querySelector("#tb").appendChild(table); } </script> </head> <body> <input type="text" id="tr_value">输入行数 <input type="text" id="td_value">输入列数 <input type="button" onclick="createTable()"; value="createTable"> <hr> <div id="tb"></div> </body> </html> |
运行结果:
输入行数、列数,create Table:
方法二.
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | <!DOCTYPE html> <html> <head> <title>动态表格</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css" rel="external nofollow" rel="external nofollow" >--> <script type="text/javascript"> var rows = prompt("输入行数:", ""); var cols = prompt("输入列数:", ""); document.write('<table width="100%" border="1px">'); document.write('<caption>成绩表</caption>'); for (var row = 1; row <= rows; row++) { if (row % 2 == 0) { document.write('<tr bgcolor=#CCCCCC>'); } else { document.write('<tr>'); } for (var col = 0; col < cols; col++) { document.write('<td height="20px"></td>'); } document.write('</tr>'); } document.write('</table>'); </script> </head> <body> </body> </html> |
运行结果:
输入行数、列数:
总结
以上所述是小编给大家介绍的利用JS动态生成隔行换色HTML表格,希望对大家有所帮助
上一篇:JS中验证整数和小数的正则表达式