如何使用列数组中的JavaScript和JQuery创建HTML表 当表的维度未知且每列中的单元格数不相同时,数组中的值。例如
[["1","4","7","10"],["2","5","8"],["3","6","9","11","12"]]
必须成为:
+----+----+----+
| 1 | 2 | 3 |
+----+----+----+
| 4 | 5 | 6 |
+----+----+----+
| 7 | 8 | 9 |
+----+----+----+
| 10 | | 12 |
+----+----+----+
| | | 11 |
+----+----+----+
答案 0 :(得分:2)
$(function () {
var cols = [["1","4","7","10"],["2","5","8"],["3","6","9","11","12"]];
var rows = [];
for (var y = 0; y < cols.length; y++) {
for (var x = 0; x < cols[y].length; x++ ) {
if (rows.length < x + 1) {
rows.push([]);
while (rows[x].length < y + 1) {
rows[x].push("");
}
}
rows[x][y] = cols[y][x];
}
}
var table_elem = $("<table></table>");
for (var x = 0; x < rows.length; x++) {
while (rows[x].length < cols.length) {
rows[x].push("");
}
var row_elem = $("<tr></tr>");
for (var y = 0; y < rows[x].length; y++) {
var cell_elem = $("<td></td>");
if (rows[x][y] != "") {
cell_elem.text(rows[x][y]);
} else {
cell_elem.html(" ");
}
row_elem.append(cell_elem);
}
table_elem.append(row_elem);
}
$("body").append(table_elem);
});
答案 1 :(得分:1)
也许你喜欢这个:
var cols = [["1","4","7","10"],["2","5","8"],["3","6","9","11","12"]];
function mkTable(cols) {
var table = $("<table></table>");
for(var y=0;;y++) {
var row = $("<tr></tr>");
var cols_left = 0;
for(i in cols) {
var col = cols[i];
var date = $('<td>');
if(col.length > y) {
date.append(col[y]);
cols_left++;
}
row.append(date);
}
if(!cols_left)
break;
table.append(row);
}
$('body').append(table);
}