实例(用JS动态生成一张成绩表)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JS操作表格的基本技巧</title> <style> table, td, th { border: 1px solid #666; } table { width: 500px; border-collapse: collapse; text-align: center; } table caption { font-size: 1.2rem; margin-bottom: 15px; } thead tr:nth-of-type(1) { background-color: lightcyan; } </style> </head> <body> <table id="cart1"> <caption>成绩表</caption> <thead> <tr> <td>编号</td> <td>姓名</td> <td>科目</td> <td>成绩</td> </tr> </thead> <tbody></tbody> </table> <script> // var cart1 = document.getElementById('cart1'); // console.log(cart1.children[2].children[1].children[1].innerText); // console.log(cart1.children[2].children[1].children[3].innerText); // cart1.children[2].children[1].children[3].innerText = 86; // 用Js对象的方式来提供数据,动态生成一个表格 // 对象数组 var data = [ {id: 1, name: '小李', subject: '数学', score: '95'}, {id: 2, name: '小王', subject: '数学', score: '80'}, {id: 3, name: '小张', subject: '数学', score: '86'} ]; var cart1 = document.getElementById('cart1'); var tbody = cart1.children[2]; //返回tbody //遍历对象数组 value是一个对象 data.forEach(function (value) { var tr = document.createElement('tr'); tr.innerHTML = '<td>' + value.id + '</td>'; tr.innerHTML += '<td>' + value.name + '</td>'; tr.innerHTML += '<td>' + value.subject + '</td>'; tr.innerHTML += '<td>' + value.score + '</td>'; tbody.appendChild(tr); }) </script> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例