2017-01-13 29 views
1

我將如何修改我的代碼(下)打開表元素(紅圈內),入表標題,然後頭每列以上(「加載「和」千瓦時「)分別爲左側和右側列?如何更好地格式化我的HTML表標題和標籤

除了表格上方標題爲「功率使用」的標題之外,還需要「名稱」和「瓦特」元素(「負載」和「千瓦時」)。現在,沒有格式化,我從W3學校的教程中遇到麻煩,進入我的代碼。

function(){ 
     var wrapper = document.createElement("div"); 
     if(!this.loaded) { 
       wrapper.innerHTML = "Loading..."; 
       return wrapper; 
     } 
     if(this.xml !== null){ 
     var table = document.createElement("table"); 
     table.classList.add("xsmall", "table"); 
     var channels = this.xml.getElementsByTagName("channel"); 

     for(var i = 0; i < channels.length; i++){ 
      var row = document.createElement("tr"); 
      for(var n = 0; n < channels[i].children.length; n++){ 
       if(channels[i].children[n].tagName === "name" || channels[i].children[n].tagName === "watts"){ 
       var element = document.createElement("td"); 
       element.classList.add(channels[i].children[n].tagName); 
       if (channels[i].children[n].textContent != 0){ 
      element.innerHTML = channels[i].children[n].textContent; 
      row.appendChild(element); 
      table.appendChild(row); 
      }  
     else { 
      table.removeChild(row); } 
     } 


      } 
     } 
     wrapper.appendChild(table); 
     } else { 
       console.log("Returned no Data"); 
       wrapper.innerHTML = "NO DATA"; 
     } 
     return wrapper; 
    }, 

的第一次嘗試: enter image description here enter image description here

回答

1

你只是想打造出類似於使用你已經寫了JS如下表:

<table> 
    <caption>Put title here</caption> 
    <thead> 
    <tr> 
     <th>Load</th> 
     <th>kWh</th> 
    </tr> 
    </thead> 
    <tbody> 
    <tr> 
     <td>Kitchen Lights</td> 
     <td>2.799</td> 
    </tr> 
    </tbody> 
</table> 
+0

注意,你可以省略' thead'和'tbody'如果你願意但是一定要用'th'而不是'td'作爲第一行來指定它是一個頭。 – DeezCashews

+0

感謝您的回覆。我在JS中遇到了麻煩。我需要2個頭部變量嗎? 'var header'和'var header2'?我不知道如何將負載與千瓦時分開。我會在我原來的帖子中添加一張照片來說明這一點。 – Gary

+1

在循環之前,只需創建一個名爲say headerRow的tr元素。然後創建兩個稱爲say header1和header2的元素。在開始在循環中添加數據之前,將它們附加到headerRow並將headerRow追加到表中。 – DeezCashews