表のソート
2346 ワード
<style>
th {cursor : pointer;}
</style>
<table border="1" id="table">
<thead>
<tr>
<th> </th>
<th> </th>
<th> </th>
</tr>
</thead>
<tbody>
<tr>
<td>23</td>
<td>1988-03-30</td>
<td>10000</td>
</tr>
<tr>
<td>21</td>
<td>1986-02-14</td>
<td>8000</td>
</tr>
<tr>
<td>25</td>
<td>1989-02-28</td>
<td>6000</td>
</tr>
</tbody>
</table>
<script>
window.onload = function() {
var ths = table.tHead.rows[0].cells;
for(var i = 0 ; i < ths.length ; i++) {
ths[i].onclick = function(i) {
return function() {
sortFun(i + 1);
};
}(i);
}
};
function sortFun(num) {
var rows = table.tBodies[0].rows;
var arr = [];
for(var i = 0 ; i < rows.length ; i++) {
arr.push(rows[i]);
}
arr.sort(window['sort' + num]);
for(var i = 0 ; i < arr.length ; i++) {
table.tBodies[0].appendChild(arr[i]);
}
}
function sort1(a , b) {
var num1 = parseInt(a.cells[0].firstChild.nodeValue);
var num2 = parseInt(b.cells[0].firstChild.nodeValue);
return num1 - num2;
}
function sort2(a , b) {
var arrs1 = a.cells[1].firstChild.nodeValue.split('-');
var arrs2 = b.cells[1].firstChild.nodeValue.split('-');
var date1 = new Date(arrs1[0] , arrs1[1] , arrs1[2]);
var date2 = new Date(arrs2[0] , arrs2[1] , arrs2[2]);
return date1.getTime() - date2.getTime() ;
}
function sort3(a , b) {
var num1 = parseInt(a.cells[2].firstChild.nodeValue);
var num2 = parseInt(b.cells[2].firstChild.nodeValue);
return num1 - num2;
}
</script>