首页 > 解决方案 > 如何按降序对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);
   }
}              

下面是图像。我想对百分比部分进行排序。

在此处输入图像描述


标签: javascripthtml

解决方案


您可能需要首先以结构化形式存储数据,以便能够对其进行排序。

我已经重新编写了您的示例以展示我的想法 - 未经测试。

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);    
}

推荐阅读