// for(var k in obj){// k -- 屬性名// obj[k] -- 屬性值// }
(效果圖)javascript
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>動態生成表格案例</title> <style> </style> </head> <body> <style type="text/css"> table.gridtable { font-family: verdana, arial, sans-serif; font-size: 11px; color: #333333; border-width: 1px; border-color: #666666; border-collapse: collapse; width: 100%; font-size: 16px; text-align: center; } table.gridtable th { border-width: 1px; padding: 8px; border-style: solid; border-color: #666666; background-color: #dedede; } table.gridtable td { border-width: 1px; padding: 8px; border-style: solid; border-color: #666666; background-color: #ffffff; } </style> <!-- Table goes in the document BODY --> <table class="gridtable"> <thead> <tr> <th>姓名</th> <th>科目</th> <th>成績</th> <th>操做</th> </tr> </thead> <tbody> </tbody> </table> <script> var data = [{ name: '小明', subject: '物理', score: '100' }, { name: 'marry', subject: '化學', score: '99' }, { name: 'luxi', subject: '語文', score: '78' }, { name: 'city', subject: '英語', score: '88' }, { name: 'city', subject: '英語', score: '88' }, { name: 'city', subject: '英語', score: '88' }, { name: 'city', subject: '英語', score: '88' }, { name: 'city', subject: '英語', score: '88' }, { name: 'city', subject: '英語', score: '88' }, { name: 'city', subject: '英語', score: '88' }, { name: 'city', subject: '英語', score: '88' }, { name: 'city', subject: '英語', score: '88' }, { name: 'city', subject: '英語', score: '88' }, { name: 'city', subject: '英語', score: '88' }, { name: 'city', subject: '英語', score: '88' }, ]; // 建立節點 var tbody = document.querySelector('tbody'); // 添加節點 // 建立行和單元格 for (var i = 0; i < data.length; i++) { // 建立tr行 var tr = document.createElement('tr'); tbody.appendChild(tr); //建立td單元格 for (var k in data[i]) { //建立單元格 var td = document.createElement('td'); tr.appendChild(td); console.log(data[i][k]); td.innerHTML = data[i][k] } // 建立刪除功能 var td = document.createElement('td'); td.innerHTML = '<a href = "javascript:;">刪除</a>'; // 添加節點 tr.appendChild(td); } // 刪除功能 var as = document.querySelectorAll('a'); for (var i = 0; i < as.length; i++) { as[i].onclick = function () { // 刪除的是a標籤所在的行(連接的父親的父親) tbody.removeChild(this.parentNode.parentNode); } } // for(var k in obj){ // k -- 屬性名 // obj[k] -- 屬性值 // } </script> </body> </html>