簡體   English   中英

如何按降序對div數據進行排序

[英]How to sort div data in descending order

我有一個 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);    
}

嘗試這個..

 // Assummed sample data var colorVariable1 = {302:"red", 156:"green", 89:"blue", 176:"orange"}; var countVariable1 = {302:30, 156:56, 89:71, 176:89}; var totalPCICount = 75; function displayLegend() { var percentages = {}; for (var key in colorVariable1) { let percentage = (countVariable1[key] / totalPCICount) * 100; percentages[key] = percentage.toFixed(2); } var sorted = Object.keys(percentages) .sort(function(a, b) { return (+percentages[a]) - (+percentages[b]) }); for (var key of sorted) { var line = document.createElement("div"); line.innerHTML = '<span class="box" style="background-color:' + colorVariable1[key] + ';"></span><span>' + key + '(' + percentages[key] + '%)</span>'; document.getElementById("legendInfo").appendChild(line); } }
 .box { width: 5px; height: 5px; padding: 5px; }
 <button onclick="displayLegend()">click</button> <div id="legendInfo"></div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM