###目的
下記テーブルの「点」「歳」(.sortdayo)にソート機能をつけたいです。
html
1<table class="sort-tab"> 2 <thead> 3 <tr> 4 <th rowspan="2">人</th> 5 <th colspan="2">歳と点</th> 6 </tr> 7 <tr> 8 <th class="sortdayo">点</th> 9 <th class="sortdayo">歳</th> 10 </tr> 11 </thead> 12 <tbody> 13 <tr> 14 <td>鈴木</td> 15 <td>1</td> 16 <td>17</td> 17 </tr> 18 <tr> 19 <td>佐藤</td> 20 <td>2</td> 21 <td>23</td> 22 </tr> 23 <tr> 24 <td>高橋</td> 25 <td>3</td> 26 <td>40</td> 27 </tr> 28 </tbody> 29</table>
###うまくいかないコード
▼実際の動作
https://jsfiddle.net/d03sg0ys/
▼コード
javascript
1$(function(){ 2 $(".sortdayo").click(function(){ 3 // culumn no you select 4 key = $(this).index(); 5 // toggle ascend or descend 6 if($(this).hasClass("descend")){ 7 var change_to = "ascend"; 8 }else{ 9 var change_to = "descend"; 10 } 11 // initialize class 12 $(this).closest("table").find("th").removeClass("ascend"); 13 $(this).closest("table").find("th").removeClass("descend"); 14 $(this).addClass(change_to); 15 // get number of line and columns of the table 16 var no_row = $(this).closest("table").children().children().length; 17 var no_column = $(this).closest("table").children().children().eq(0).children().length; 18 // get all entries and keep values in array 19 var arr = []; 20 21 // flag for value type "strings" or "number only" 22 var flag = 0; // 0:number only 1:strings 23 var re = /\D/; 24 25 for(var i=1; i < no_row; i++){ 26 arr[i-1]=[]; 27 for(var j=0; j < no_column; j++){ 28 if(j==key && re.test($(this).closest("table").children().children().eq(i).children().eq(j).text())){ 29 flag=1; 30 } 31 arr[i-1][j] = $(this).closest("table").children().children().eq(i).children().eq(j).text(); 32 } 33 } 34 35 // sort by the key you selected 36 var rs = arr.sort( 37 function(a,b){ 38 //case : value type is number only 39 if(flag==0){ 40 if(change_to == "ascend"){ 41 return(a[key] - b[key]); 42 }else{ 43 return(b[key] - a[key]); 44 } 45 //case : value contains strings 46 }else{ 47 if(change_to == "ascend"){ 48 if(a[key] > b[key]){ 49 return 1; 50 }else{ 51 return -1; 52 } 53 }else{ 54 if(b[key] > a[key]){ 55 return 1; 56 }else{ 57 return -1; 58 } 59 } 60 } 61 } 62 ) 63 64 // insert arranged values into table 65 for(var i=0;i < rs.length; i++){ 66 for(var j=0;j < rs[i].length; j++){ 67 $(this).closest("table").children().children().eq(i+1).children().eq(j).text(rs[i][j]); 68 } 69 } 70 }); 71});
やってみたこと、調べたことを具体的に記述願います。あと確認したブラウザなど環境情報もあわせて。