这是使用我在评论中提到的方法动态构建的示例。
CSS
.tableCSS, th, td {
border: 1px solid;
}
.tableCSS thead {
font-weight: bold;
}
Javascript
var array = [],
codePointAt,
length,
i;
array.push({
a: "A",
b: "B",
c: "C"
});
array.push({
a: "a1",
b: "b1",
c: "c1"
});
array.push({
a: "a2",
b: "b2",
c: "c3"
});
array.push({
a: "a3",
b: "b3",
c: "c3"
});
function convertSpaces(text) {
return text.replace(/ /g, "\u00a0");
}
for (i = 1, length = array.length; i < length; i += 1) {
var object = array[0],
table = document.createElement("table"),
thead = document.createElement("thead"),
tbody = document.createElement("tbody"),
tr,
td,
pre,
j;
table.className = "tableCSS";
table.appendChild(thead);
table.appendChild(tbody);
tr = thead.insertRow();
for (j in object) {
if (object.hasOwnProperty(j)) {
td = document.createElement("th");
td.appendChild(document.createTextNode(convertSpaces(object[j])));
tr.appendChild(td);
}
}
tr = tbody.insertRow();
object = array[i];
for (j in object) {
if (object.hasOwnProperty(j)) {
td = tr.insertCell(),
td.appendChild(document.createTextNode(convertSpaces(object[j])));
}
}
pre = document.createElement("pre");
pre.appendChild(table);
console.log(pre.innerHTML);
document.body.appendChild(table);
}
在jsfiddle
和输出innerHTML
<table class="tableCSS"><thead><tr><th>A</th><th>B</th><th>C</th></tr></thead><tbody><tr><td>c1</td><td>b1</td><td>a1</td></tr></tbody></table>
<table class="tableCSS"><thead><tr><th>A</th><th>B</th><th>C</th></tr></thead><tbody><tr><td>c3</td><td>b2</td><td>a2</td></tr></tbody></table>
<table class="tableCSS"><thead><tr><th>A</th><th>B</th><th>C</th></tr></thead><tbody><tr><td>c3</td><td>b3</td><td>a3</td></tr></tbody></table>