实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>js操作表格的基本技巧</title> <style> table,th,td{ border: 1px solid #666; } table { width: 500px; text-align: center; border-collapse: collapse; } table caption { font-size: 1.2rem; margin-bottom: 15px; } /* 这里必须在nth-of-type(1)前添加父元素,否则thead,tbody中的第一行都会生效 */ thead tr:nth-of-type(1) { background-color: lightblue; } </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></tbody> </table> <script> //模拟动态生成表格 var data = [ {id: 1, name: '牛奶', count: 3, price: 50}, {id: 2, name: '苹果', count: 10, price: 80}, {id: 3, name: '衣服', count: 2, price: 600} ]; //获取到table var cart1 = document.getElementById('cart1'); // 获取到table下的tbody var tbody = cart1.children[2]; for (let index = 0; index < data.length; index++) { var tr = document.createElement('tr'); tr.innerHTML = '<td>' + data[index].id + '</td>'; tr.innerHTML += '<td>' + data[index].name + '</td>'; tr.innerHTML += '<td>' + data[index].count + '</td>'; tr.innerHTML += '<td>' + data[index].price + '</td>'; tbody.appendChild(tr); } </script> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例