jQuery实现任意列表或表格的排序

目录

html

一般表格 table 的结构应该是:

<table>
  <thead>
    <tr>
      <th>head1</th>
      <th>head2</th>
      <th>head3</th>
      <th>head4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>b</td>
      <td>300</td>
      <td>你好</td>
    </tr>
    <tr>
      <td>3</td>
      <td>a</td>
      <td>100</td>
      <td>第一弹</td>
    </tr>
    <tr>
      <td>2</td>
      <td>c</td>
      <td>300</td>
      <td>斯干</td>
    </tr>
  </tbody>
</table>

js

jQ脚本(满足上面表格结构的直接用就好):

{#表格排序01#}
$(document).on('click', 'th', function() {
  var table = $(this).parents('table').eq(0);
  var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()));
  this.asc = !this.asc;
  if (!this.asc) {
    rows = rows.reverse();
  }
  table.children('tbody').empty().html(rows);
});
{#表格排序02#}
function comparer(index) {
  return function(a, b) {
    var valA = getCellValue(a, index),
      valB = getCellValue(b, index);
    return $.isNumeric(valA) && $.isNumeric(valB) ?
      valA - valB : valA.localeCompare(valB);
  };
}
{#表格排序03#}
function getCellValue(row, index) {
  return $(row).children('td').eq(index).text();
}

分析:

{#表格排序01#}
$(document).on('click', 'th', function() {  {#监视表头点击#}
  var table = $(this).parents('table').eq(0);   {#点击表头时,取得表格的<table>元素#}
  var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()));  {#找到<tbody>中所有<tr>,并排序;($(this).index()获取点击列的列序号)#}
  this.asc = !this.asc; {#每次点击反向排序#}
  if (this.asc) {   {#默认首次点击逆序排列#}
    rows = rows.reverse();  {#排序后<tr>替换原始<tr>#}
  }
  table.children('tbody').empty().html(rows);
});
{#表格排序02#}
function comparer(index) {
  return function(a, b) {
    var valA = getCellValue(a, index),  {#得到本<tr>的第index列的值#}
      valB = getCellValue(b, index);
    return $.isNumeric(valA) && $.isNumeric(valB) ?
      valA - valB : valA.localeCompare(valB);   {#可对数字和字符串进行排序,以相减的值进行排序;(数字以数值大小排序,字符串先转为数值型再按数值型排序)#}
  };
}
{#表格排序03#}
function getCellValue(row, index) { {#取得row行index列的值#}
  return $(row).children('td').eq(index).text();    {#从row行find第index列的值#}
}

** 表格结构比较复杂的要自定义下getCellValue() Function **

Last Updated: 2019/12/6 18:34:45