jquery.tablesorter.jsを使ってテーブル(table)の見出し(th)タグをクリックすると、その要素(tdタグ)が降順・昇順でソート(sort)する方法をご紹介します。
Contents
ディスプレイ広告
テーブル(table)をソートするCSSの記述
※必要に応じて変更して下さい。
<style type="text/css"> <!-- body { margin: 0px; font-size:14px; } h1{ font-size:16px; font-weight:normal; line-height:1.4em; text-align:center; padding:15px 0 10px 0; } #idWrap{ width:700px; margin:0 auto; } table{ border:solid 1px #333333; } th{ background-color:#333333; color:#FFFFFF; border-bottom:solid 1px #333333; cursor:pointer; } th:hover{ background-color:#FFFFFF; color:#333333; border-bottom:solid 1px #333333; } th, td{ padding:10px; font-weight:normal; } --> </style>
jquery.tablesorter.jsを使ってテーブル(table)をソート(sort)するJavaScriptの記述
※jqueryとjquery.tablesorter.jsファイルを読み込みます。$(‘#myTable’).tablesorter()でソートしたいテーブル(id=”myTable”)を指定します。
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script> <script src="jquery.tablesorter.js"></script> <script type="text/javascript"> $(function(){ $('#myTable').tablesorter(); }); </script>
jquery.tablesorter.jsを使ってテーブル(table)をソート(sort)するHTMLの記述
※ソートさせたいテーブル(table)の記述です。テーブルの見出し(th)タグをクリックするとその要素(tdタグ)が降順・昇順でソート(sort)されます。
<table id="myTable" cellpadding="0" cellspacing="0"> <thead> <tr> <th>No</th> <th>Category</th> <th>URL</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>css</td> <td><a href="https://dad-union.com/category/css" target="_blank">https://dad-union.com/category/css</a></td> </tr> <tr> <td>2</td> <td>JavaScript</td> <td><a href="https://dad-union.com/category/javascript" target="_blank">https://dad-union.com/category/javascript</a></td> </tr> <tr> <td>3</td> <td>jQuery</td> <td><a href="https://dad-union.com/category/jquery" target="_blank">https://dad-union.com/category/jquery</a></td> </tr> <tr> <td>4</td> <td>PHP</td> <td><a href="https://dad-union.com/category/php" target="_blank">https://dad-union.com/category/php</a></td> </tr> </tbody> </table>
テーブルタグをソート可能にするデモページ
対応ブラウザはIE 6.0+, FF 2+, Safari 2.0+, Opera 9.0+の様です。Chromeでも大丈夫そうです。
※流用される場合は自己責任でお願いします。
デモページタグ内のGoogleアナリティクスタグは流用しないで下さい。