利用JS动态生成隔行换色HTML表格的两种方法
程序员文章站
2022-03-07 22:47:31
用js生成动态生成表格,行、列由用户输入,并使表格隔行换色
方法一.
代码:
&l...
用js生成动态生成表格,行、列由用户输入,并使表格隔行换色
方法一.
代码:
<!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:
方法二.
代码:
<!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表格,希望对大家有所帮助
上一篇: 从零开始用electron手撸一个截屏工具的示例代码
下一篇: python大杂铺