1 回答
TA贡献1853条经验 获得超18个赞
由于您已经在表格中创建行并按行显示,因此我认为您需要按列显示它(转置)。因此,一种解决方案是使用相等数量的列和行构建您的。trs
然后将行中的数据显示为列,反之亦然
maximum count
在下面的代码中,我首先从您的 json 数组中获取了。然后,我减去所有 json 数组的max value
with count
,然后根据这个,我向该行附加了额外的 tds。现在,您的表按行显示,row
并且columns
然后,我使用each
循环遍历trs
之前生成的循环,并tds
在新的trs
最后删除之前添加了所有内容trs
。
下面的图片将帮助您了解差异。
演示代码:
var json = [{
"fight_declaration": 1,
"count": 2
},
{
"fight_declaration": 3,
"count": 4
},
{
"fight_declaration": 2,
"count": 6
},
{
"fight_declaration": 4,
"count": 6
}
]
var counts;
//loop through json arrays to get max count
for (var i = 0; i < json.length; i++) {
if (!counts || parseInt(json[i]["count"]) > parseInt(counts["count"]))
counts = json[i];
}
var data = '';
data += "<table>"
$.each(json, function(key, val) {
if (val.count > 1) {
data += '<tr>'
for (let i = 0; i < val.count; i++) {
add_colors(val.fight_declaration); //call function to color
}
//get extra tds to add in row..respect to max value
var new_count = counts.count - val.count
while (new_count > 0) {
//add extra tds
data += '<td></td>'
new_count--;
}
data += '</tr>'
} else {
add_colors(val.fight_declaration);
}
})
data += "</table>"
//loop through html generated
var datas = $(data).each(function() {
var $this = $(this);
var newrows = [];
//loop through rows
$this.find("tr").each(function() {
var i = 0;
//get tds
$(this).find("td").each(function() {
if (newrows[i] === undefined) {
newrows[i] = $("<tr></tr>");
}
newrows[i].append($(this));
i++;
});
});
//remove previous trs
$this.find("tr").remove();
//add new trs
$.each(newrows, function() {
$this.append(this);
});
});
//add value to the table
$("table.trend-table").html($(datas).html())
function add_colors(values) {
if (values == 1) {
data += '<td><span class="red-dot">R</span></td>'
} else if (values == 2) {
data += '<td><span class="blue-dot">B</span></td>'
} else if (values == 3) {
data += '<td><span class="green-dot">G</span></td>'
} else if (values == 4) {
data += '<td><span class="yellow-dot">Y</span></td>'
}
}
.red-dot {
background-color: red;
}
.blue-dot {
background-color: blue;
}
.green-dot {
background-color: green;
}
.yellow-dot {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="trend-table">
</table>
添加回答
举报