javascript - 如何按降序对div数据进行排序
问题描述
我有一个显示特定颜色百分比的 div。我想按降序对 div 百分比进行排序。如何进行?下面是我的代码
function displayLegend() {
for (var key in colorVariable1) {
let percentage = (countVariable1[key] / totalPCICount) * 100;
if(percentage) {
percentage = percentage.toFixed(2);
}
var line = document.createElement("div");
line.innerHTML = '<span class="box" style=" background: ' + colorVariable1[key] + ';"></span><span>' + key + '(' + percentage + '%)</span>';
document.getElementById("legendInfo").appendChild(line);
}
}
下面是图像。我想对百分比部分进行排序。
解决方案
您可能需要首先以结构化形式存储数据,以便能够对其进行排序。
我已经重新编写了您的示例以展示我的想法 - 未经测试。
var values = []; // holder for rows
for (var key in colorVariable1) {
let percentage = (countVariable1[key] / totalPCICount) * 100;
if(percentage) {
percentage = percentage.toFixed(2);
} else {
percentage = 0;
}
// row definition
let entry = {
value: percentage,
html: '<span class="box" style=" background: ' + colorVariable1[key] + ';"></span><span>' + key + '(' + percentage + '%)</span>';
}
values.push(entry); // add row to holder
}
// sort rows in holder by value (percentage)
// see: https://stackoverflow.com/questions/979256/sorting-an-array-of-objects-by-property-values
values.sort(function(a, b) {
return parseFloat(b.value) - parseFloat(a.value);
});
// add sorted lines
for(var i in values){
var line = document.createElement("div");
line.innerHTML = values[i].html;
document.getElementById("legendInfo").appendChild(line);
}
推荐阅读
- google-cloud-platform - 我应该如何更改查询以便对 BigQuery 中数组的每条记录应用函数?
- python - 为什么pywt小波变换的输出是复数数组?
- java - 如何在 Atlas 中使用标签过滤
- shopify - 在 Shopify 产品描述中隐藏文本
- gem5 - 无法在 Gem5 核心转储问题上运行 SpectreSafeInvisibleSpec 方案
- linux - 如何从 tar.gz 中仅提取所需的文件?
- operating-system - 内页表缺页是否会产生缺页?
- c - 用平行边改变字符串位置中的字符值,例如 yuv = vuy
- android - 如何在 Cloud Firestore 中使用文档 ID 执行集合组查询
- kotlin - 从 kotlin 中另一个列表中的对象更新列表中的对象