LoginSignup
1
1

TableSorter( jQuery plug-in)で簡単に表のソートを実装する。

Last updated at Posted at 2015-07-23

#概要

  • クライアント側で表の基本的なソートを簡単に実装したい。
  • TableSorter(jQuery plug-in)を使用。
  • CSSに関しては、ドキュメンテーションが参考にならなかったので、試行錯誤の結果です。

Screenshot 2015-07-22 20.00.14.png

#環境
Ruby 2.2.1
Rails 4.2.2

#やり方

準備

ドキュメンテーションに従い、TableSorterを対象のアプリケーションに追加してください。

View

HAMLで書きました。基本的なHTMLのtableです。ポイントは2つです。

  1. jQueryが表を探すためのIDをtableタグにつけておきます。
  2. 後にCSSにより三角印のアイコンを挿入する目的で、空spanタグを予め書いておきます。
%table#myTable
  %thead
    %tr
      %th
        %span.arrow
          / <=ここにアイコンを挿入する。
      %th
        %span.arrow
          / <=ここにアイコンを挿入する。
      %th{ span: "2" }
  %tbody
    %tr
      %td 列1データ1
      %td 列1データ2
      %td ...
      %td ...
    %tr
      %td 列2データ1
      %td 列2データ2
      %td ...
      %td ...
    ...

jQuery

CoffeeScriptで書きました。対象の表に対して、TableSorterを呼び出します。これで表にソート機能が追加されます。

$(document).ready ->
  $("#myTable").tablesorter()

CSS(オプション)

CSSを何も設定しなくてもソートは既に実装されていますが、お好みで見た目を変更したい場合はCSSを操作します。
僕の場合は、下記の通りになりました。ヘッダーをクリックするとソートの状態を示すCSSクラスが自動的に追加されます。この振る舞いを利用して、ソートの状態に応じて見た目を変更します。

/* ヘッダーをクリックすると勝手にハイライトされるので、それを除去する。 */

th:focus { outline: 0 none; }

/* 三角印アイコンをヘッダーに追加する */

th.tablesorter-headerUnSorted span.arrow,
th.tablesorter-headerAsc span.arrow,
th.tablesorter-headerDesc span.arrow {
  position: relative;
}

th.tablesorter-headerUnSorted span.arrow:before {
  content: "\f0dc";
  font-family: FontAwesome;
  font-style: normal;
  font-weight: normal;
  text-decoration: inherit;
  color: #ABC;
}

th.tablesorter-headerAsc span.arrow:before {
  content: "\f0de";
  font-family: FontAwesome;
  font-style: normal;
  font-weight: normal;
  text-decoration: inherit;
}

th.tablesorter-headerDesc span.arrow:before {
  content: "\f0dd";
  font-family: FontAwesome;
  font-style: normal;
  font-weight: normal;
  text-decoration: inherit;
}

参考文献

1
1
0

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
1
1