Correction status:Uncorrected
Teacher's comments:
1.获取到页面中的表格的元素id值和当前表格的tbody(tBodies是复数)
2.使用for遍历对象数组获取到下标,再使用forEach遍历获取到对象数组中的值,动态生成行,把数据插入到行内
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>动态生成表格数据(创建对象数组,使用循环遍历动态生成渲染到页面)2019.05.09</title> <style> table,th,td{ border:1px solid #666; } table{ margin:0 auto; width:500px; text-align:center; border-collapse: collapse; } table caption{ font-size:1.2rem; margin-bottom: 15px } thead tr:nth-of-type(1){ background-color: lightblue; } </style> </head> <body> <table id="cart1"> <caption>购物车1</caption> <thead> <tr> <th>编号</th> <th>品名</th> <th>数量</th> <th>单价</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>手机</td> <td>1</td> <td>5000</td> </tr> <tr> <td>1</td> <td>水果</td> <td>6</td> <td>800</td> </tr> <tr> <td>1</td> <td>笔记本</td> <td>9</td> <td>6000</td> </tr> <tr> <td>1</td> <td>手提</td> <td>1</td> <td>500</td> </tr> </tbody> </table> <table id="cart2"> <caption>购物车1</caption> <thead> <tr> <th>编号</th> <th>品名</th> <th>数量</th> <th>单价</th> </tr> </thead> <tbody></tbody> </table> <table id="cart3"> <caption>购物车1</caption> <thead> <tr> <th>编号</th> <th>品名</th> <th>数量</th> <th>单价</th> </tr> </thead> <tbody></tbody> </table> <script> //创建对象数组 var data = [ {id: 1, name: '牛奶', count: 3, price: 50}, {id: 1, name: '苹果', count: 10, price: 80}, {id: 1, name: '衣服', count: 2, price: 600} ]; //获取表格2 var tbody = document.getElementById('cart2'); //遍历对象数组 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.count + '</td>'; tr.innerHTML += '<td>' + value.price + '</td>'; tbody.appendChild(tr); }); var cart3 = document.getElementById('cart3'); var tbody = cart3.tBodies[0]; for(var i = 0;i < data.length; i++){ var tr = document.createElement('tr'); Object.keys(data[i]).forEach(function(key){ tr.innerHTML += '<td>'+data[i][key]+'</td>'; }); tbody.appendChild(tr); } </script> </body> </html>
点击 "运行实例" 按钮查看在线实例