用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表格,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
标签:
js,动态生成,js隔行换色表格
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
狼山资源网 Copyright www.pvsay.com
暂无“利用JS动态生成隔行换色HTML表格的两种方法”评论...