문제

I have a results set of data that includes page numbers

<div class="results">
   <div class="result" data-pages="1005-1007">
      pp 1005-1007
   </div>
   <div class="result" data-pages="997">
      pp 997
   </div>
   <div class="result" data-pages="1009-1012">
      pp 1009-1012
   </div>
   <div class="result" data-pages="1037-1038">
     pp 1037-1038
  </div>

A simple sort would re-order these if they were integers:

$('.result').sort(function(a,b){
   return $(a).data('pages') >$(b).data('pages');
}).appendTo('.results')

But the ranges throw off the results, unsurprisingly the function above is unhelpful:

pp 1005-1007
pp 997
pp 1009-1012
pp 1037-1038

How can I use javascript/jquery to reorder these results into something that will give me:

pp 997
pp 1005-1007
pp 1009-1012
pp 1037-1038

http://jsfiddle.net/craigjb12/CFYnE/63/

도움이 되었습니까?

해결책

You canreturn -1 or 1 from the sort function

$('.result').sort(function (a, b) {
    return $(a).data('pages') > $(b).data('pages') ? -1 : 1;
}).appendTo('.results')

Demo: Fiddle

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top