1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
   |  <!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <title>Document</title>     <!-- <script src="web20.json"></script> -->     <!-- <link rel="stylesheet" href="web20.json"> --> </head> <body>     <table border="1" width="80%" align="center">         <tr>             <th>姓名</th>             <th>年龄</th>             <th>性别</th>             <th>爱好</th>         </tr>         <tbody id="tbd">                      </tbody>         
          <!-- <tr>             <td>李四</td>             <td>19</td>             <td>男</td>             <td>唱歌</td>         </tr> -->     </table>
      <script>     //假设jons已经拿到手了,到了当前页面了     //数据     var json={         "web19":[{             "name":"王宇铨",             "age":18,             "sex":"男",             "hobby":["电影","敲代码"]         },{             "name":"刘莹",             "age":19,             "sex":"女",             "hobby":["音乐","敲代码"]         },{             "name":"徐欢",             "age":18,             "sex":"女",             "hobby":["码字","做饭"]         }],         "web20":[{             "name":"王宇铨2",             "age":18,             "sex":"男",             "hobby":["电影2","敲代码"]         },{             "name":"刘莹2",             "age":19,             "sex":"女",             "hobby":["音乐2","敲代码"]         }]     };
      // 通过遍历该对象循环生成结构即可     var web20=json.web20;     var tbd=document.getElementById("tbd");     var html="";//     // 第一重循环,外循环,拿到的是第一层数据     // 第二层循环,内循环,拿到的是具体的要解析的那个对象     for(prop in json){         console.log(prop);//web19,web20         console.log(json[prop]);//[],[] 两个数组遍历出来         for(pp in json[prop]){             console.log(pp);//0,1,2             console.log(json[prop][pp]);//每一位学生             //性能问题             //tbd.innerHTML+=,操作了多次DOM结构             //操作DOM是有代价的             //HTML是如何渲染的,DOM树更新后,需要重绘视图             html+=`<tr>                         <td>${json[prop][pp].name}</td>                         <td>${json[prop][pp].age}</td>                         <td>${json[prop][pp].sex}</td>                         <td>${json[prop][pp].hobby}</td>                     </tr>`;         }
      }     // 一次性插入到结构中,只操作了一次DOM     tbd.innerHTML=html;
      </script> </body> </html>
 
 
  |