利用jq的sort()方法对页面元素dom进行升降序排列

  ·   jQuery   ·   HTML     浏览量:

先写到这里后面再优化

html

1.排序按钮

<span class="box">
  <span id="sort-down">由高到低</span>
  <span id="sort-up" class="focus">由低到高</span>
</span>

2.dom列表

<div class="grade" id="sort-box">
      <div class="once">
        <span class="school">测试小学</span>
        <div class="limit">
          <span class="slide" style="width:70%;">&nbsp;</span>
          <span class="percent">70%</span>
        </div>
      </div>
      <div class="once">
        <span class="school">测试小学</span>
        <div class="limit">
          <span class="slide" style="width:60%;">&nbsp;</span>
          <span class="percent">60%</span>
        </div>
      </div>
      <div class="once">
        <span class="school">测试小学</span>
        <div class="limit">
          <span class="slide" style="width:30%;">&nbsp;</span>
          <span class="percent">30%</span>
        </div>
      </div>
      <div class="once">
        <span class="school">测试小学</span>
        <div class="limit">
          <span class="slide" style="width:80%;">&nbsp;</span>
          <span class="percent">80%</span>
        </div>
      </div>
      <div class="once">
        <span class="school">测试小学</span>
        <div class="limit">
          <span class="slide" style="width:30%;">&nbsp;</span>
          <span class="percent">30%</span>
        </div>
      </div>
    </div>

jq代码

  //降序排列
  $('body').on('click','#sort-down', function(){
    var domList = $('#sort-box .once').get();
    domList.sort(function(a,b){
      var elOne = $(a).find('.percent').text();
      var elTwo = $(b).find('.percent').text();
      if(elOne > elTwo) return 1;
      if(elOne < elTwo) return -1;
      return 0;
    });
    $('#sort-box').append(domList)
  });
  //升序排列
  $('body').on('click','#sort-up', function(){
    var domList = $('#sort-box .once').get();
    domList.sort(function(a,b){
      var elOne = $(a).find('.percent').text();
      var elTwo = $(b).find('.percent').text();
      if(elOne > elTwo) return -1;
      if(elOne < elTwo) return 1;
      return 0;
    });
    $('#sort-box').append(domList)
  });


收起 >>
利用jq的sort()方法对页面元素dom进行升降序排列