我正在使用 jQuery 解析 JSON 数据并使用 AJAX 加载到表中,但如何使 td 元素仅合并在一行中?不要介意标题的位置,我只是担心数据。
我的结果:
这是正确的:
代码:
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "@Url.Action("FlatType", "Home", new {id = TempData["Id"] })",
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
let $thead = $('#myColumns'),
$tr = $('<tr>');
console.log(data);
data.data.forEach(col => {
$tr.append($('<th>').html(col === null || col === "" ? 0 : col));
console.log(col);
});
$thead.append($tr);
}
});
$.ajax({
type: "POST",
url: "@Url.Action("FlatTypeById", "Home", new {id = TempData["Id"] })",
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
let $tbody = $('#myData');
data.data.forEach(row => {
let $tr = $('<tr>');
$tr.append(row.map(val => {
return $('<td>').html(val === null || val === "" ? 0 : val);
}));
$tbody.append($tr);
});
}
});
});
</script>
JSON 数组数据:这是列:
{
"data": [
[
"ID",
"TYPE",
"TOTAL",
"1 bed room",
"2 bed room"
]
]
}
JSON 数组数据:这是数据:
{
"data": [
[
"100",
"Total Transaction Amount",
"9812355000",
"23397000",
"13976000"
],
[
"100",
"No. of units",
"1268",
"3",
"2"
],
[
"100",
"(Total sq.ft.)",
"",
"",
""
],
[
"100",
"Avg. price",
"7738450",
"7799000",
"6988000"
],
[
"100",
"Avg. sq.ft.",
"",
"",
""
],
[
"100",
"Max. price",
"25494000",
"9918000",
"7318000"
],
[
"100",
"Max. sq.ft",
"",
"",
""
],
[
"100",
"Min. price",
"5904000",
"6465000",
"6658000"
],
[
"100",
"Min. sq.ft",
"",
"",
""
]
]
}
最佳答案
我认为您的意思是将所有组加在一起,即每组一行。 对数据进行排序,如下所示:
group1
group1
group1
group2
group2
group2
group3
group3
...
然后您可以使用控制中断算法对其进行迭代:
var curKey = 0;
var curRow = myArray[curKey];
var newGroup = myArray.someColumn;
var oldGroup = newGroup;
while (typeof curRow !== "undefined") {
while (newGroup === oldGroup && typeof curRow !== "undefined" {
// sum your group here
curKey++;
curRow = myArray[curKey];
newGroup = myArray.someColumn;
}
oldGroup = newGroup;
}
未经过测试,也从未在 JavaScript 中完成过。但是,是的,我想你有这种感觉。您的数据似乎来自后端。在后端排序应该更容易。
您还可以以面向对象的方式更昂贵(且未排序)地完成此示例。
关于javascript - 如何使用 jQuery 将 2 个 td 合并到一个 td 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42758398/