用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>
運行結果:
輸入行數、列數:
*僅供參考,轉載請註明
*代碼①參考:https://www.cnblogs.com/hwgok/p/5739822.html#4080148