<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> #box table thead { background-color: lightgray; } #box table { border-collapse: collapse; text-align: center; border: 1px solid black; width: 300px; } #box table tr, #box table th { border: 1px solid black; } </style> </head> <body> <div id="box"></div> <script> // 表数据 datas = [{name: 'zs', sub: '语文', score: 100}, {name: 'ls', sub: '数学', score: 90}, {name: 'ww', sub: '语文', score: 100} ]; // 表头数据 var dataHeads = ['姓名', '科目', '成绩', '操作']; var box = document.getElementById('box'); // 1,创建table元素 var table = document.createElement('table'); box.appendChild(table); // 2,创建表头 var thead = document.createElement('thead'); table.appendChild(thead); var tr = document.createElement('tr'); thead.appendChild(tr); // 创建表头内容 for (var i=0; i < dataHeads.length; i++) { var th = document.createElement('th'); tr.appendChild(th); th.innerText = dataHeads[i]; } var tbody = document.createElement('tbody'); table.appendChild(tbody); // 创建表格 for (var i=0; i < datas.length; i++) { data = datas[i]; tr = document.createElement('tr'); tbody.appendChild(tr); for (var key in data) { th = document.createElement('th'); tr.appendChild(th); th.innerText = data[key]; } td = document.createElement('td'); tr.appendChild(td); var link = document.createElement('a'); td.appendChild(link); // 移除超链接的跳转 link.href = 'javascript:void(0)'; link.innerText = '删除'; // 删除超链接 注册事件 link.onclick = linkDelete; function linkDelete() { // 获取父节点 var tr = this.parentNode.parentNode; tbody.removeChild(tr); // 取消a的超链接 return false; } } </script> </body> </html>