1 回答

TA貢獻1853條經驗 獲得超18個贊
由于您已經在表格中創建行并按行顯示,因此我認為您需要按列顯示它(轉置)。因此,一種解決方案是使用相等數量的列和行構建您的。trs
然后將行中的數據顯示為列,反之亦然
maximum count
在下面的代碼中,我首先從您的 json 數組中獲取了。然后,我減去所有 json 數組的max value
with count
,然后根據這個,我向該行附加了額外的 tds?,F在,您的表按行顯示,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>
添加回答
舉報