前端学习笔记day12 动态创建元素之创建表格 实现动态删除
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Document</title> <style> #box table { border-collapse: collapse; } </style> <script src="common.js"></script> </head> <body> <div id='box'></div> <script> var data = [ {name: '璇璇',age: 23,gender: '女'}, {name: '西西',age: 23,gender: '女'}, {name: '宣萱',age: 23,gender: '女'}, {name: '哼哼',age: 23,gender: '女'}, {name: '依依',age: 23,gender: '女'}, ] var headData = ['姓名','年龄','性别','操作']; var box = document.getElementById('box'); var table = document.createElement('table'); // 设置表格的边框以及宽度; table.border = '1px'; table.width = '400px'; table.style.textAlign = 'center'; box.appendChild(table); var thead = document.createElement('thead'); table.appendChild(thead); var tr = document.createElement('tr'); thead.appendChild(tr); var tbody = document.createElement('tbody'); table.appendChild(tbody); // 添加表头信息 for (var i = 0;i<headData.length;i++) { var th = document.createElement('th'); setInnerText(th,headData[i]) tr.appendChild(th); } for (var i = 0;i < data.length;i++) { var tr = document.createElement('tr') tbody.appendChild(tr); for (var key in data[i]) { var td = document.createElement('td'); setInnerText(td,data[i][key]); tr.appendChild(td); } var td = document.createElement('td'); var link = document.createElement('a'); link.href = 'javascript:void(0)'; td.appendChild(link); tr.appendChild(td); setInnerText(link,'删除'); link.onclick = removeLine; } </script> </body> </html>
function setInnerText(element,value) { if (typeof element.innerText) { element.innerText = value; }else { element.textContent = value; } } function removeLine () { tr = this.parentNode.parentNode; tbody.removeChild(tr); }
运行结果:
talk is cheap,show me the code