Sort jQuery list by two attributes

后端 未结 1 708
情话喂你
情话喂你 2021-01-19 07:14

I\'ve this markup:

#a(data-row=\"2\", data-col=\"3\") a
#b(data-row=\"1\", data-col=\"1\") b
#c(data-row=\"1\", data-col=\"3\") c
#d(data-row=\"2\", data-col         


        
相关标签:
1条回答
  • 2021-01-19 08:00

    The second value is only applicible if the first values are equal, so this should do it for you:

    var gridElements = $('div');
    gridElements.sort(function (a, b) {
      var contentA =parseInt( $(a).attr('data-row'));
      var contentB =parseInt( $(b).attr('data-row'));
    
    
      //check if the rows are equal
      if (contentA === contentB) {
         var colA = parseInt( $(a).attr('data-col'));
         var colB = parseInt( $(b).attr('data-col'));
    
         //do the same as your already doing but using different data, from above
         return (colA < colB) ? -1 : (colA > colB) ? 1 : 0;
      }
      else {
        return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
      }
    });
    
    0 讨论(0)
提交回复
热议问题