Correction status:qualified
Teacher's comments:
在实际开发中我们经常会遇到从后台取到数据后,动态添加到前端页面的情况,本篇将通过对模拟的data对象数组的操作
实现js对数据的动态添加
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <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.2em; } thead tr:nth-of-type(1){ background-color: lawngreen; } </style> </head> <body> <table id="cart1"> <caption>购物车1</caption> <!-- 注: 浏览器会自动给以下内容添加一个tbody容器 --> <!-- 为防止作用js获取元素出错,我们手工添加上这个tbody --> <!-- 将表头手工加上thead,否则会被添加二个tbody,因为table允许使用多个tbody --> <thead> <tr> <th>编号</th> <th>品名</th> <th>数量</th> <th>单价</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>手机</td> <td>1</td> <td>3000</td> </tr> <tr> <td>2</td> <td>电脑</td> <td>1</td> <td>5000</td> </tr> <tr> <td>3</td> <td>手机</td> <td>1</td> <td>3000</td> </tr> </tbody> </table> <button onclick="add()">动态添加</button> <button onclick="add2()">动态添加2</button> </body> <script> var data = [ {id: 1, name: '牛奶', count: 3, price: 50}, {id: 1, name: '苹果', count: 10, price: 80}, {id: 1, name: '衣服', count: 2, price: 600} ]; function add() { tbody = document.getElementsByTagName('tbody')[0]; //第一种遍历数组的方法 forEach data.forEach(function(v,k) { var tr = document.createElement('tr'); tr.innerHTML = "<td>"+v.id+"</td><td>"+v.name+"</td><td>"+v.count+"</td><td>"+v.price+"</td>"; tbody.appendChild(tr); }); } function add2() { tbody = document.getElementsByTagName('tbody')[0]; //第二种遍历用for循环遍历data 再用forEach遍历键值 for(i=0;i<data.length;i++){ var tr = document.createElement('tr'); Object.keys(data[i]).forEach(function(k) { tr.innerHTML += "<td>"+ data[i][k] + "</td>"; }); tbody.appendChild(tr); } } </script> </html>
点击 "运行实例" 按钮查看在线实例