簡體   English   中英

從javascript數組填充HTML表

[英]Populate an HTML table from javascript array

我有一個腳本數組:

var lakeData = [
{
   "Month": "1959-01",
   "LakeErieLevels": 12.296
 },
 {
   "Month": "1959-02",
   "LakeErieLevels": 13.131
 },
 {
   "Month": "1959-03",
   "LakeErieLevels": 13.966
 },
 {
   "Month": "1959-04",
   "LakeErieLevels": 15.028
 },
 {
   "Month": "1959-05",
   "LakeErieLevels": 15.844
 },
 {
   "Month": "1959-06",
   "LakeErieLevels": 15.769
 }
 ];

我有點HTML代碼:

<table id="lake">
  <thead><tr><th>Date</th><th>Depth</th></tr></thead>
  <tbody></tbody>
</table>

而且我正試圖在頁面加載時讓數組填充到表中。

 var lakeData = [{ "Month": "1959-01", "LakeErieLevels": 12.296 }, { "Month": "1959-02", "LakeErieLevels": 13.131 }, { "Month": "1959-03", "LakeErieLevels": 13.966 }, { "Month": "1959-04", "LakeErieLevels": 15.028 }, { "Month": "1959-05", "LakeErieLevels": 15.844 }, { "Month": "1959-06", "LakeErieLevels": 15.769 } ]; function addDataToTbody(nl, data) { // nl -> NodeList, data -> array with objects data.forEach((d, i) => { var tr = nl.insertRow(i); Object.keys(d).forEach((k, j) => { // Keys from object represent th.innerHTML var cell = tr.insertCell(j); cell.innerHTML = d[k]; // Assign object values to cells }); nl.appendChild(tr); }) } var lakeTbody = document.querySelector("#lake tbody"); addDataToTbody(lakeTbody, lakeData); 
 <table id="lake"> <thead> <tr> <th>Date</th> <th>Depth</th> </tr> </thead> <tbody></tbody> </table> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM