<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>toList</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: #ccc; } </style> </head> <body> <table id="list"> <caption>文具列表</caption> <thead> <th>序号</th> <th>名称</th> <th>单价</th> <th>数量</th> </thead> <tbody> </tbody> </table> <script> var data = [//创建js数据数组 {id:1, product:'铅笔', price:20, number:30 }, {id:2, product:'橡皮', price:30, number:40 }, {id:3, product:'***', price:40, number:50 }, {id:4, product:'本子', price:50, number:60 } ]; var list = document.getElementById('list');//通过获取id获取元素list var tbody = list.tBodies[0];//获取list表格的第一个tbody for(i = 0;i < data.length; i++){//用for循环,定义变量i,与数组data长度作比较 var tr = document.createElement('tr');//创建tr元素 Object.keys(data[i]).forEach(function(key){//用forEach遍历数组data tr.innerHTML += '<td>' + data[i][key] + '</td>';//将td元素及data中内容写入tr中 }) tbody.appendChild(tr); //在tbody中添加tr } </script> </body> </html>