利用JS动态生成隔行换色HTML表格
程序员文章站
2023-11-02 14:20:58
用JS生成动态生成表格,行、列由用户输入,并使表格隔行换色 方法一. 代码: 运行结果: 输入行数、列数,create Table: 方法二. 代码: 运行结果: 输入行数、列数: *仅供参考,转载请注明 *代码①参考:https://www.cnblogs.com/hwgok/p/5739822. ......
用js生成动态生成表格,行、列由用户输入,并使表格隔行换色
方法一.
代码:
1 <!doctype html> 2 <html> 3 <head> 4 <title>动态表格</title> 5 6 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 7 <meta http-equiv="description" content="this is my page"> 8 <meta http-equiv="content-type" content="text/html; charset=utf-8"> 9 10 <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> 11 <script type="text/javascript"> 12 function createtable(){ 13 var table = document.createelement("table"); 14 //添加边框 15 table.border = "1"; 16 table.width = "100%"; 17 18 //table api 19 //创建一行 20 //var tr = table.insertrow(table.rows.length); 21 //创建单元格 22 //var td = tr.insertcell(tr.cells.length); 23 //行,单元格 24 var tr,td; 25 //获得行列值 26 var tr_value = document.getelementbyid("tr_value").value; 27 var td_value = document.getelementbyid("td_value").value; 28 for(var i=0;i<tr_value;i++){ 29 //循环插入元素 30 tr = table.insertrow(table.rows.length); 31 if(i%2 === 0){ 32 tr.style.backgroundcolor = "#d5e3d0"; 33 }else{ 34 tr.style.backgroundcolor = "#909c97"; 35 } 36 for(var j=0;j<td_value;j++){ 37 td = tr.insertcell(tr.cells.length); 38 td.innerhtml = "_"; 39 td.align = "center"; 40 41 } 42 } 43 44 //td.innerhtml = "测试"; 45 46 document.queryselector("#tb").appendchild(table); 47 } 48 </script> 49 </head> 50 51 <body> 52 <input type="text" id="tr_value">输入行数 53 <input type="text" id="td_value">输入列数 54 <input type="button" onclick="createtable()"; value="createtable"> 55 <hr> 56 <div id="tb"></div> 57 </body> 58 </html>
运行结果:
输入行数、列数,create table:
方法二.
代码:
1 <!doctype html> 2 <html> 3 <head> 4 <title>动态表格</title> 5 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 6 <meta http-equiv="description" content="this is my page"> 7 <meta http-equiv="content-type" content="text/html; charset=utf-8"> 8 <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> 9 <script type="text/javascript"> 10 var rows = prompt("输入行数:", ""); 11 var cols = prompt("输入列数:", ""); 12 document.write('<table width="100%" border="1px">'); 13 document.write('<caption>成绩表</caption>'); 14 for (var row = 1; row <= rows; row++) { 15 if (row % 2 == 0) { 16 document.write('<tr bgcolor=#cccccc>'); 17 } else { 18 document.write('<tr>'); 19 } 20 for (var col = 0; col < cols; col++) { 21 document.write('<td height="20px"></td>'); 22 } 23 document.write('</tr>'); 24 } 25 document.write('</table>'); 26 </script> 27 28 </head> 29 <body> 30 31 </body> 32 </html>
运行结果:
输入行数、列数:
*仅供参考,转载请注明
上一篇: 手机LPDDR5和LPDDR4X内存还傻傻分不清?带你一文看懂
下一篇: 1.泛型(Generic)