1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <title>Document</title>
    7. <style>
    8. .box{
    9. width: 500px;
    10. }
    11. </style>
    12. </head>
    13. <body>
    14. <div class="box">
    15. </div>
    16. <script>
    17. let users=[
    18. {
    19. id:1,
    20. name:"Lynn",
    21. age:18
    22. },
    23. {
    24. id:2,
    25. name:"Lynn",
    26. age:18
    27. },
    28. {
    29. id:3,
    30. name:"Lynn",
    31. age:18
    32. },
    33. {
    34. id:4,
    35. name:"Lynn",
    36. age:18
    37. }
    38. ]
    39. function init(){
    40. //使用dom技术给box添加表格
    41. let box=document.querySelector('.box');
    42. let table=document.createElement('table');
    43. // 将table元素添加到box
    44. box.appendChild(table);
    45. let thead=document.createElement('thead');
    46. table.appendChild(thead);
    47. let tr=document.createElement('tr');
    48. thead.appendChild(tr);
    49. let th=document.createElement('th');
    50. th.appendChild(document.createTextNode('id'));
    51. tr.appendChild(th);
    52. th=document.createElement('th');
    53. th.appendChild(document.createTextNode('姓名'));
    54. tr.appendChild(th);
    55. th=document.createElement('th');
    56. th.appendChild(document.createTextNode('年龄'));
    57. tr.appendChild(th);
    58. let tbody=document.createElement('tbody');
    59. table.appendChild(tbody);
    60. for(let user of users){
    61. tr=document.createElement('tr');
    62. let td=null;
    63. for(let key in user){
    64. td=document.createElement('td');
    65. // user[key]--取出变量key这个属性所对应的值
    66. td.appendChild(document.createTextNode(user[key]));
    67. tr.appendChild(td);
    68. }
    69. tbody.appendChild(tr);
    70. }
    71. }
    72. window.onload=function(){
    73. init();
    74. }
    75. </script>
    76. </body>
    77. </html>