动态表格
第一步:构建DOM结构:
<table id="cart1"> <caption>购物车1</caption> <thead> <tr> <th>编号</th> <th>品名</th> <th>数量</th> <th>单价</th> </tr> </thead> <tbody></tbody> </table>
第二步:用数组模拟数据表
var data = [{ id: 1, name: '牛奶', count: 3, price: 50 }, { id: 1, name: '苹果', count: 10, price: 80 }, { id: 1, name: '衣服', count: 2, price: 600 } ];
第三步:获取表格的节点
var cart1 = document.getElementById('cart1');
第四步:获取tbody的节点
var tbody = cart1.children[2];
第五步:遍历数组
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);
实例
<!DOCTYPE html> <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: lightblue; } </style> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Page Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" media="screen" href="main.css" /> <script src="main.js"></script> </head> <body> <table id="cart1"> <caption>购物车1</caption> <thead> <tr> <th>编号</th> <th>品名</th> <th>数量</th> <th>单价</th> </tr> </thead> <tbody></tbody> </table> </body> </html> <script> // data是一个对象数组 var data = [{ id: 1, name: '牛奶', count: 3, price: 50 }, { id: 1, name: '苹果', count: 10, price: 80 }, { id: 1, name: '衣服', count: 2, price: 600 } ]; var cart1 = document.getElementById('cart1'); var tbody = cart1.children[2]; 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); }); </script>
运行实例 »
点击 "运行实例" 按钮查看在线实例
总结:动态表格的制作对forEach的掌握有一定要求。