我想用colspan创建一个html表头,但是我迷路了;我有这个json:
var metadata = [{
"colIndex": 0,
"colType": "String",
"colName": "PM"
}, {
"colIndex": 1,
"colType": "String",
"colName": "PROD"
}, {
"colIndex": 2,
"colType": "Numeric",
"colName": "NR/M1"
}, {
"colIndex": 3,
"colType": "Numeric",
"colName": "NR/M2"
}, {
"colIndex": 4,
"colType": "Numeric",
"colName": "NR/M3"
}, {
"colIndex": 5,
"colType": "Numeric",
"colName": "NR/M4"
}, {
"colIndex": 6,
"colType": "Numeric",
"colName": "NR/M5"
}, {
"colIndex": 7,
"colType": "Numeric",
"colName": "NR ART/M6"
}, {
"colIndex": 8,
"colType": "Numeric",
"colName": "NR ART/M1"
}, {
"colIndex": 9,
"colType": "Numeric",
"colName": "NR ART/M2"
}, {
"colIndex": 10,
"colType": "Numeric",
"colName": "NR ART/M3"
}, {
"colIndex": 11,
"colType": "Numeric",
"colName": "NR ART/MX"
}];
表格标题主要基于拆分“ colType”:“ Numeric”
+------+-------+-----+--------+-----+-----+-----+-----+------+----+----+----+
| | | NR | NR ART |
+ PAM | PROD +-----+--------+-----+-----+-----+-----+------+----+----+----+
| | M1 | M2 | M3 | M4 | M5 | M6 | M1 | M2 | M3 | MX |
+------+-------+-----+--------+-----+-----+-----+-----+------+----+----+----+
首先我尝试在colType为数字的情况下拆分colName
var arr = [], a;
$.each(metadata, function (i, v) {
arr.push(v.colName.split("/"));
a = v.colName.split("/").length;
});
接下来,我得到了唯一的父母(?),但是我该怎么办?我认为我必须遍历此数组(父级-子级,然后构造html标头)。
该数组是动态的。
有什么建议吗?谢谢,麻烦您了。
几个小时后,我找到了解决我问题的答案。在第一部分中,我创建了tr和th(第一个非唯一的)
var a = [], l = 0;
for (var i = 0; i < metadata.length; i++) {
var d = {
"colName": metadata[i].colName.split("/"),
"colType": metadata[i].colType
};
a.push(d);
if (metadata[i].colType == "Numeric") {
trl = metadata[i].colName.split("/").length;
}
}
for (var l = 0; l < trl; l++) {
var tr = $("<tr/>").appendTo("thead");
}
for (var j = 0; j < a.length; j++) {
if (a[j].colType == "String") {
$("<th/>").addClass("string").attr("rowspan", l).html(a[j].colName).appendTo("thead tr:nth(0)");
} else {
for (var k = 0; k < a[j].colName.length; k++) {
$("<th/>").addClass("numeric").html(a[j].colName[k]).appendTo("thead tr:nth(" + k + ")");
}
}
}
这部分从这里改编。现在,我收拾桌子thead居住只是独特的。
$('table tr').each(function () {
var tr = this;
var counter = 0;
var strLookupText = '';
$('th.numeric', tr).each(function (index, value) {
var td = $(this);
if ((td.text() == strLookupText) || (td.text() == "")) {
counter++;
td.prev().attr('colspan', '' + parseInt(counter + 1, 10) + '').css({
textAlign: 'center'
});
td.remove();
} else {
counter = 0;
}
strLookupText = td.text();
});
});
代码有点混乱,但是已经晚了。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句