Skip to content

Instantly share code, notes, and snippets.

@thomasjao
Last active August 29, 2015 14:23
Show Gist options
  • Save thomasjao/85036b55923815594a1f to your computer and use it in GitHub Desktop.
Save thomasjao/85036b55923815594a1f to your computer and use it in GitHub Desktop.
Generate Table with Head Using JSON as source
function showData( data ) {
var docs = data;
if ( Array.isArray( docs )) {
var tbl = document.createElement('table');
var tr = document.createElement('tr');
/* 表格標題列 */
var titles = Object.keys(data[0]);
var tr = document.createElement('tr');
for (var i in titles) {
var th = document.createElement('th');
th.innerText = titles[i];
th.setAttribute('class', 'thcss');
tr.appendChild(th);
}
tbl.appendChild(tr);
/* 表格內容 */
for (var i=0; i<docs.length; i++) {
var tr = document.createElement('tr');
for (var j in docs[i]) {
var td = document.createElement('td');
td.innerText = docs[i][j];
tr.appendChild(td);
}
tbl.appendChild(tr);
}
document.body.appendChild(tbl);
}
}
/* data : JSON Source */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment