按数据属性对Asc和Desc进行排序

时间:2017-08-05 08:53:57

标签: javascript

我很难确定如何根据两个数据属性对列表进行排序。我想通过data-name和data-id对它进行排序,包括升序和降序。请帮帮我吧!

<a href="#" class="pure-button sort2">Name A - Z <i class="fa fa-arrow-up"></i></a>
<a href="#" class="pure-button sort1">Name Z - A <i class="fa fa-arrow-up"></i></a>
<div class="sort-list"> 
  <div data-id="1" data-name ="afres">Anchor</div>
  <div data-id="2" data-name="bottom">Anchor</div>
  <div data-id="3" data-name="curves">Curves</div>
</div>

&#13;
&#13;
function sortMeBy(arg, sel, elem, order) {
  var $selector = $(sel),
    $element = $selector.children(elem);

  $element.sort(function(a, b) {
    var an = a.getAttribute(arg),
      bn = b.getAttribute(arg);

   if (order == 'asc') {
      if (an > bn)
        return 1;
      if (an < bn)
        return -1;
    } else if (order == 'desc') {
      if (an < bn)
        return 1;
      if (an > bn)
        return -1;
    }
    return 0;
  });

  $element.detach().appendTo($selector);
}

$(document).on('click', '.sort1', function() {
  sortMeBy('data-id', 'div.sort-list', 'div', 'desc');
});
$(document).on('click', '.sort2', function() {
  sortMeBy('data-id', 'div.sort-list', 'div', 'asc');
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="pure-button sort2">Name A - Z <i class="fa fa-arrow-up"></i></a>
    <a href="#" class="pure-button sort1">Name Z - A <i class="fa fa-arrow-up"></i></a>
    <div class="sort-list"> 
      <div data-id="5.5" data-name="afres">Anchor</div>
      <div data-id="2.2" data-name="bottom">Bottom</div>
      <div data-id="3.1" data-name="curves">Curves</div>
    </div>
&#13;
&#13;
&#13;

我试图返回a > b,但它不起作用。 请帮帮我!

0 个答案:

没有答案