勉強したことのメモ

Webエンジニア / プログラマが勉強したことのメモ。

簡単にtable内をソート

   2014/07/03  jQuery

やりたかった事は、

・テーブル内でのソート

・内容は文字、数値、日時

PHPじゃなくてjQueryプラグインを使って短時間で実装したい

以上。出来る限りシンプルなものを探したところ

軽くて目当てのものを発見。

■参考サイト

http://joequery.github.io/Stupid-Table-Plugin/

■サンプル

http://sample.taitan916.info/sort/

■使い方

jQueryプラグインを読み込む。

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="./stupidtable.min.js"></script>

<th>のところに、

・文字⇒data-sort="string"

・数値⇒data-sort="int"

・日時⇒data-sort="date"

をつける。

あと<tbody>~</tbody><thead>~</thead>がいるみたい。

■ソース

<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="./stupidtable.min.js"></script>
<script>
$(function(){
$("#simpleTable").stupidtable();
});
</script>

<style>

.sorting-asc, .sorting-desc {

background-color: #ff0000;

}

</style>
<title>Stupid jQuery Table Sortのテスト</title>
</head>
<body>
<h1>Stupid jQuery Table Sortのテスト</h1>
<table border="1" id="simpleTable">
<thead>
<tr>
<th>ソート無し</th><th data-sort="string" style="cursor:pointer;">名前</th><th data-sort="int" style="cursor:pointer;">数字</th><th data-sort="date" style="cursor:pointer;">時間</th>
</tr>
</thead>
            <tbody>
<tr>
<td>ここはソートなし</td><td>山田</td><td>252</td><td>2013-01-05 23:59:10</td>
</tr>
<tr>
<td>ソート無しです</td><td>川口</td><td>157</td><td>2012-01-25 10:22:44</td>
</tr>
<tr>
<td>ソート無し</td><td>なまえ</td><td>9</td><td>2013-01-04 10:22:45</td>
</tr>
<tr>
<td>ソート無し無し</td><td>かに玉</td><td>52</td><td>2012-01-25 10:22:45</td>
</tr>
<tr>
<td>ソーとなし</td><td>あいう</td><td>10</td><td>2019-01-25 10:22:45</td>
</tr>
  </tbody>
</table>
</body>
</html>

■その他

ソートすると<th>のところに、

class=sorting-asc

class=sorting-desc

が付与される。なので、CSSで指定して、

ソートしたやつは色変えたりとかすると分かりやすい。

あとソートする<th>のところにはCSSマウスポインタ

変えると視覚的にも分かりやすい。

 - jQuery

  関連記事

jQueryにてCookieを取り扱う「jquery-cookie」プラグインの利用方法

jQueryでcookieを簡単に取り扱える「jquery-cookie」プラグ ...

CodeIgniter4 & jQueryを用いて同一サイト内でajax通信する方法

CodeIgniter4.4.4 & jQueryを用いて同一サイト内で ...

jQueryにてclosestの使いどころとparent / parentsとの違いについて

あるソースコードを見ているとjQueryにてclosest()という使ったことの ...

tableタグでスクロール時にヘッダーを残して表示する方法(jquery-decapitate)

テーブルタグ内で縦にスクロールした際にテーブルヘッダー部分は表示させたままテーブ ...

IE11でフォーム送信時に二重登録される

Internet Explorer11でform送信時にデータが二重登録されると ...