1. 程式人生 > 其它 >JS動態生成表格

JS動態生成表格

<style>
        .box {
            display: flex;
            justify-content: center;
        }
        
        table {
            width: 600px;
            text-align: center;
            border-collapse: collapse;
            border: 1px solid #000;
        }
        
        table thead {
            background-color
: #ccc; } table tr td { border: 1px solid #000; } </style> </head> <body> <div class="box"> <table> <thead> <tr> <td colspan="4"><strong>成績表</
strong></td> </tr> <tr> <td>姓名</td> <td>科目</td> <td>成績</td> <td>操作</td> </tr> </thead> <
tbody> </tbody> </table> </div> </body> <script> var tb = document.querySelector('tbody'); // 動態生成表格,可以自己生成幾個物件來模擬資料庫 function Results(uName, course, result) { this.uName = uName; this.course = course; this.result = result; } var xy = new Results('小雨', '數學', 99); var xh = new Results('小紅', '語文', 88); var xm = new Results('小明', '英文', 89); var xl = new Results('小林', '物理', 77); var xm = new Results('小馬', '化學', 98); var xw = new Results('小王', '數學', 69); // 使用陣列把資料存進去 var obj = [xy, xh, xm, xl, xm, xw]; // 建立tr標籤把資料顯示出來 for (var i = 0; i < obj.length; i++) { var tr = document.createElement('tr'); tb.appendChild(tr); var td1 = document.createElement('td'); td1.innerHTML = obj[i].uName; var td2 = td1.cloneNode(true); td2.innerHTML = obj[i].course; var td3 = td1.cloneNode(true); td3.innerHTML = obj[i].result; var td4 = td1.cloneNode(true); td4.innerHTML = '<a href="javascript::">刪除</a>'; tr.appendChild(td1); tr.appendChild(td2); tr.appendChild(td3); tr.appendChild(td4); } var as = tb.querySelectorAll('a'); for (var i = 0; i < as.length; i++) { as[i].onclick = function() { tb.removeChild(this.parentNode.parentNode); } } </script>