在js中添加到表中

时间:2016-03-10 05:47:34

标签: javascript json html-table

我正在尝试将<th>标记添加到表中,但我无法添加。我想将IdNameProf添加为表格标题。

var obj=[{id:"01",name:"Bob",prof:"Soft Engg"},{id:"02",name:"George",prof:"Admin"},{id:"03",name:"Paul",prof:"Front End"}];
var table = document.createElement("table");
table.setAttribute("id","myTable");
document.body.appendChild(table);

for(i=0;i<obj.length;i++) {
  var row = document.createElement("tr")
  table.appendChild(row);
  var head = document.createElement("th");
  row.appendChild(head);
  for (key in obj[i]) {
    var cell = document.createElement("td");
    row.appendChild(cell);
    cell.innerHTML = obj[i][key];
  }
}

2 个答案:

答案 0 :(得分:2)

你可以做这样的事情

&#13;
&#13;
var obj = [{
  id: "01",
  name: "Bob",
  prof: "Soft Engg"
}, {
  id: "02",
  name: "George",
  prof: "Admin"
}, {
  id: "03",
  name: "Paul",
  prof: "Front End"
}];
var table = document.createElement("table");
table.setAttribute("id", "myTable");
document.body.appendChild(table);

// check array length
if (obj.length) {
  // create row for table head
  var row = document.createElement("tr")
  // append it to table
  table.appendChild(row);
  // get kesys from first object and iterate
  Object.keys(obj[0]).forEach(function(v) {
    // create th
    var cell = document.createElement("th");
    // append to tr
    row.appendChild(cell);
    // update th content as key value
    cell.innerHTML = v;
  });
}

for (var i = 0; i < obj.length; i++) {
  var row = document.createElement("tr")
  table.appendChild(row);
  for (key in obj[i]) {
    var cell = document.createElement("td");
    row.appendChild(cell);
    cell.innerHTML = obj[i][key];
  }
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我无法停止思考这篇文章并将其用作JS练习,我在这里:

var obj=[
{id:"01",name:"Bob",prof:"Soft Engg"},
{id:"02",name:"George",prof:"Admin"},
{id:"03",name:"Paul",prof:"Front End"}
];

var headers=['id','name','prof'];

var table = document.createElement("table");
table.setAttribute("id","myTable");
document.body.appendChild(table);

var tableHeader = document.createElement("thead");
table.appendChild(tableHeader);
tableHeaderRow = document.createElement("tr");
table.appendChild(tableHeaderRow);
for(i=0;i<headers.length;i++){
        var tableHeader = document.createElement("th");
        tableHeaderRow.appendChild(tableHeader);
        tableHeader.innerHTML = headers[i]
}

var tableBody = document.createElement("tbody");
  table.appendChild(tableBody);
 for(i=0;i<headers.length;i++){
    var tbodyrows=document.createElement("tr");
 for (key in obj[i]) {
    tableBody.appendChild(tbodyrows);
    var cell = document.createElement("td");
    tbodyrows.appendChild(cell);
    cell.innerHTML = obj[i][key];
  }
}