简体   繁体   中英

Sort divs by multiple data attributes

How can I sort by both of the data attributes? First I need to sort by discount and then sort by weight .

<div id="list">
    <div class="row" data-weight="1" data-discount=0>banana</div>
    <div class="row" data-weight="3" data-discount=30>apple</div>
    <div class="row" data-weight="4" data-discount=0>avocado</div>
    <div class="row" data-weight="8" data-discount=15>milk</div>
</div>
function sortOrder(){
  divList.sort(function(a, b){ 
    return $(b).data("order")-$(a).data("order")
  });
  $(".list").html(divList);
}

Your current sort() logic shows how to do this for a single attribute. For multiple attributes you simply need to amend the logic to cater for cases where the values are the same, which can be seen below.

Note that this logic can be made less verbose, but I left it this way to make the flow more obvious.

 var $divList = $('#list .row'); function sortOrder() { $divList.sort(function(a, b) { var $a = $(a), $b = $(b); if ($a.data('discount') < $b.data('discount')) { return 1; } else if ($a.data('discount') > $b.data('discount')) { return -1; } if ($a.data('weight') < $b.data('weight')) { return 1; } else if ($a.data('weight') > $b.data('weight')) { return -1; } return 0; }); $("#list").append($divList); } sortOrder(); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="list"> <div class="row" data-weight="1" data-discount=0>banana</div> <div class="row" data-weight="3" data-discount=30>apple</div> <div class="row" data-weight="4" data-discount=0>avocado</div> <div class="row" data-weight="8" data-discount=15>milk</div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM