Correction status:Uncorrected
Teacher's comments:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>操作表格</title> <style> table,th,td{ border: 1px solid #666; } table { width: 500px; text-align: center; border-collapse: collapse; } table caption { font-size: 1.2rem; margin-bottom: 15px; } /* 这里必须在nth-of-type(1)前添加父元素,否则thead,tbody中的第一行都会生效 */ thead tr:nth-of-type(1) { background-color: lightblue; } </style> </head> <body> <table id="table"> <caption>花名册</caption> <thead> <tr> <th>编号</th> <th>姓名</th> <th>年龄</th> <th>性别</th> </tr> </thead> <tbody id="tbody"></tbody> </table> <script> var data = [ {id: 0, name: '张三', age: 15, male: '男'}, {id: 1, name: '李四', age: 18, male: '女'}, {id: 2, name: '王五', age: 23, male: '未知'} ]; //先获取要添加表单的位置1、先获取表格 var table=document.getElementById('table'); var tbody=table.tBodies[0]; for(var i=0;i<data.length;i++){ //先在tbody下创建一组<tr></tr>标签 var tr=document.createElement('tr'); Object.keys(data[i]).forEach(function (value) { tr.innerHTML= tr.innerHTML + '<td>'+data[i][value]+'</td>'; }); tbody.appendChild(tr); } </script> </body> </html>
点击 "运行实例" 按钮查看在线实例