LoginSignup
9
9

More than 5 years have passed since last update.

jqueryでつくるテーブルのソート機能(ドットインストール)

Posted at

テーブルのソート機能

<!DOCTYPE>
<html>
<head>
     <meta charset=“UTF-8”>
     <title>jQuery Table Sort</title>
</head>
<body>

<table>
     <thead>
          <tr>
               <th class =“dothesort" data-type=“string”>名前<span></span></th>
               <th class=“dothesort” data-type=“integer">点数<span></span></th>
          </tr>
     </thead>
     <tbody>
          <tr>
               <td>taguchi</td>
               <td>32</td>
          </tr>
          <tr>
               <td>fkoji</td>
               <td>4</td>
           </tr>
           <tr>
               <td>dotinstall</td>
               <td>23</td>
            </tr>
            <tr>
               <td>takahashi</td>
               <td>12</td>
             </tr>
     </tbody>
<table>
</table>
<script src=“http://code.jquery.com/jquery-1.10.2.min.js”></script>
<script>
$(function(){

//並び替え順を設定
var sortOrder = 1; //1:昇順, -1:降順
//列をクリックしたら
     $(‘.dothesort’).click(function(){

          var type = $(this).data(’type’);
          var col = $(this).index(); //0, 1 ...

          //行全体を取得
          var $rows = $(’tbody>tr’);

          //行を並び替え(点数で)
          $rows.sort(function(a,b){
               return compare(a, b, type)*sortOrder;

          var arrow.empty.append($rows);

          var arrow = sortOrder === 1 ? “▲”:”▼”;
          $(‘.dothesort > span’).text('’);
          $(this).find(’span’).text(arrow)
          //並び替え順を反転
          sortOrder *= -1;
     });

     function  compare(a, b, type, col){
               var  _a = $(a).find(’td’).eq(col).text() *1;
               var  _b = $(b).find(’td’)eq(col).text() *1;

               if(type == “string”){
                    if(_a < _b)
                         return -1;
                    } 
                    if(_a > _b){
                         return 1;
                    }
                    return 0;
          } else {
               _a *= 1;
               _b *= 1;
               return _a - _b
              }


     }

});
</script>
</body>
<html>
9
9
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9