How to sort divs by 2 data attributes?

后端 未结 3 1252
孤城傲影
孤城傲影 2021-01-21 06:42

How do I modify my code so that it sorts by both data-status and then data-order? ie the desired result is 1,2,3,4

I need to support IE.

3条回答
  •  無奈伤痛
    2021-01-21 07:07

    To sort by multiple attributes you simply need to put the secondary sorting logic in place where the two primary attributes match. This can be done in a ternary, as in the following example.

    Also note that given your HTML the output will be 1,2,4,3 as the order of the 4 element is lower than that of the 3.

    $(document.body).on('click', "#sortthem", function() {
      $(".sortme").sort(function(a, b) {
        let $a = $(a), $b = $(b);
        let aStatus = $a.data('status'), bStatus = $b.data('status');
        let aOrder = $a.data('order'), bOrder = $b.data('order');
            
        return aStatus < bStatus ? -1 : 
          aStatus > bStatus ? 1 : 
          aOrder < bOrder ? -1 :
          aOrder > bOrder ? 1 : 0;
      }).appendTo('#mydivs');
    });
    4
    3
    2
    1
    Sort them

提交回复
热议问题