实例
<DOCTYPE html> <head> <meta charset=utf-8> <title></title> <style type="text/css"> table,td,th{ border: 1px solid #ccc; } table { width:600px; border-collapse:collapse; text-align:center;} table caption{ color:red; font-weight: bold; margin-bottom: 10px; } thead tr{background-color:lightblue;} /*thead tr:nth-of-type(1){background-color:lightblue;}*/ </style> </head> <!-- table对象定义一些属性,可以快速获取指定的子元素 1.tHead :<thead> 2.Tbodies :<tbody>----复数 3.tFoot :<tfoot> 4.rows :所有行 5.cells :所有列 --> <table id="cart1"> <caption>购物车</caption> <thead> <tr> <th>编号</th> <th>品名</th> <th>数量</th> <th>单价</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>手机</td> <td>2</td> <td>5000</td> </tr> <tr> <td>2</td> <td>电脑</td> <td>3</td> <td>6000</td> </tr> <tr> <td>3</td> <td>电视</td> <td>2</td> <td>3000</td> </tr> </tbody> </table> <hr> <table id="cart2"> <caption>购物车</caption> <thead> <tr> <th>编号</th> <th>品名</th> <th>数量</th> <th>单价</th> </tr> </thead> <tbody></tbody> </table> <!-- <script type="text/javascript"> var cart1 =document.getElementById('cart1'); var comput =cart1.tBodies[0].rows[1].cells[3].innerHTML = 7000; </script> --> <script type="text/javascript"> var data = [ {id:1,name:'牛奶',count:3,price:50}, {id:2,name:'苹果',count:10,price:80}, {id:3,name:'衣服',count:2,price:200} ] var cart2 = document.getElementById('cart2'); var tbody = cart2.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); // }) for(var i = 0;i<data.length;i++){ var tr = document.createElement('tr'); Object.keys(data[i]).forEach(function (value){ tr.innerHTML +='<td>' + data[i][value] + '</td>'; tbody.appendChild(tr); } ) } </script> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例