#概要
- クライアント側で表の基本的なソートを簡単に実装したい。
- TableSorter(jQuery plug-in)を使用。
- CSSに関しては、ドキュメンテーションが参考にならなかったので、試行錯誤の結果です。
#環境
Ruby 2.2.1
Rails 4.2.2
#やり方
準備
ドキュメンテーションに従い、TableSorterを対象のアプリケーションに追加してください。
View
HAMLで書きました。基本的なHTMLのtableです。ポイントは2つです。
- jQueryが表を探すためのIDをtableタグにつけておきます。
- 後に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;
}