如何使 jQuery table 排序器始终在最后一列进行初始排序?

How do I make the jQuery table sorter always initially sort on the last column?

我正在使用 JQuery table分拣机 v 2.0。我目前是这样设置的

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

但是如何将默认排序顺序设置为始终是 table 中的最后一列?硬编码数字可能不理想的原因是因为我正在动态生成 table 数据,有时 table 会有五列,有时会有六列。

您可以计算 table 中 headers 的数量,并使用它来获取最后一列索引。例如:

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

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

您可以编写一个 jQuery 插件来计算给定 table 的 table headers 的数量(也考虑列跨度)。

下面的示例数据来自 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>jsmith@gmail.com</td>
      <td>.00</td>
      <td>http://www.jsmith.com</td>
    </tr>
    <tr>
      <td>Bach</td>
      <td>Frank</td>
      <td>fbach@yahoo.com</td>
      <td>.00</td>
      <td>http://www.frank.com</td>
    </tr>
    <tr>
      <td>Doe</td>
      <td>Jason</td>
      <td>jdoe@hotmail.com</td>
      <td>0.00</td>
      <td>http://www.jdoe.com</td>
    </tr>
    <tr>
      <td>Conway</td>
      <td>Tim</td>
      <td>tconway@earthlink.net</td>
      <td>.00</td>
      <td>http://www.timconway.com</td>
    </tr>
  </tbody>
</table>