2017-02-07 20 views
2

私はJQuery tablesorter v 2.0を使用しています。私は現在、このように設定していますjQueryテーブルソーターを最初に最後の列でソートする方法を教えてください。

$("#myTable").tablesorter({ 
    sortList: [[4,0]] 
}); 

しかし、いつもテーブルの最後の列になるようにデフォルトの並べ替え順序を設定しますか?数字をハードコーディングするのが理想的ではない理由は、テーブルのデータを動的に生成しているため、テーブルに5つのカラムがあり、6つあることがあるからです。

答えて

1

テーブル内のヘッダーの数を数え、最後の列インデックスを取得するために使用できます。たとえば:

// Get the number of "th" within the first "tr": 
var columnCount = $('table tr:first').children('th').length; 

$("#myTable").tablesorter({ 
    sortList: [[columnCount - 1, 0]] 
}); 
+0

これは...動作する別の可能性の理想的な答えですが、あなたは小さなテーブルを持っている場合にのみ、 '$(「番目のテーブルのTHEAD:最後」)を追加することです。初期化コード([demo](http://jsfiddle.net/eY8uH/1823/))の後にclick(); – Mottie

1

あなたは(だけでなく、列スパンを占める)与えられたテーブルのテーブルヘッダの数をカウントjQueryプラグインを書くことができます。

以下のサンプルデータは、docsの開始のセクションからのものです。

(function($) { 
 
    $.fn.colCount = function() { 
 
    var colCount = 0; 
 
    this.find('tr:first-child td').each(function() { 
 
     colCount += $(this).attr('colspan') ? +$(this).attr('colspan') : 1; 
 
    }); 
 
    return colCount; 
 
    }; 
 
})(jQuery); 
 

 
$(document).ready(function() { 
 
    $('#myTable').tablesorter({ 
 
    sortList: [ 
 
     [$('#myTable').colCount() - 1, 0] 
 
    ], 
 
    theme : 'dropbox' 
 
    }); 
 
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.28.5/css/theme.dropbox.min.css" rel="stylesheet"/> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.28.5/js/jquery.tablesorter.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.28.5/js/jquery.tablesorter.widgets.min.js"></script> 
 
<table id="myTable" class="tablesorter"> 
 
    <thead> 
 
    <tr> 
 
     <th>Last Name</th> 
 
     <th>First Name</th> 
 
     <th>Email</th> 
 
     <th>Due</th> 
 
     <th>Web Site</th> 
 
    </tr> 
 
    </thead> 
 
    <tbody> 
 
    <tr> 
 
     <td>Smith</td> 
 
     <td>John</td> 
 
     <td>[email protected]</td> 
 
     <td>$50.00</td> 
 
     <td>http://www.jsmith.com</td> 
 
    </tr> 
 
    <tr> 
 
     <td>Bach</td> 
 
     <td>Frank</td> 
 
     <td>[email protected]</td> 
 
     <td>$50.00</td> 
 
     <td>http://www.frank.com</td> 
 
    </tr> 
 
    <tr> 
 
     <td>Doe</td> 
 
     <td>Jason</td> 
 
     <td>[email protected]</td> 
 
     <td>$100.00</td> 
 
     <td>http://www.jdoe.com</td> 
 
    </tr> 
 
    <tr> 
 
     <td>Conway</td> 
 
     <td>Tim</td> 
 
     <td>[email protected]</td> 
 
     <td>$50.00</td> 
 
     <td>http://www.timconway.com</td> 
 
    </tr> 
 
    </tbody> 
 
</table>

関連する問題