如何使用标题和标签更好地格式化HTML表格

时间:2017-01-13 18:46:02

标签: javascript html xml dom

如何修改我的代码(如下所示)以将表格元素(用红色圈出)转换为带有标题的表格,然后将每个列上方的标题("加载"和"左列和右列分别为kWh")?

元素," name"和"瓦特"是我想为("加载""千瓦时")创建标签,以及表格上方标题为" Power Usage"。现在,没有格式化,我无法从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 个答案:

答案 0 :(得分: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>