实例
<!DOCTYPE html> <html lang = "en"> <head> <meta charset = "UTF-8"> <title>使用JS将数据显示到表格中</title> <style> table { width: 500px; } table, th, td { border: 1px solid #DDDDDD; /*collapse ke`laps 坍方*/ border-collapse: collapse; text-align: center; } thead { background-color: lightblue; } table caption { font-size: 1.2em; margin-bottom: 15px; } </style> </head> <body> <div> <table> <caption>购物车</caption> <thead> <tr> <th>序号</th> <th>商品名称</th> <th>数量</th> <th>单价</th> </tr> </thead> <tbody> </tbody> </table> </div> <script> //模拟数据库取出来的数据 var data = [ {id: 1, name: '牛奶', count: 16, price: 40}, {id: 2, name: '瓜子', count: 2, price: 15}, {id: 3, name: '鸡翅', count: 2, price: 30}, {id: 4, name: '水蜜桃', count: 3, price: 6} ]; // 数据展示在表格中 // table对象定义的属性,快速获取指定的子元素 // tHead, tBodies, tFoot, rows, cells var tbody = document.getElementsByTagName('table')[0].tBodies[0]; //使用array对象的forEach方法遍历数组 data.forEach(function (value) { // console.log(value.name); 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> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例