【问题标题】:DataTables sort mixed numeric and text columnDataTables 对混合的数字和文本列进行排序
【发布时间】:2021-04-28 13:54:09
【问题描述】:

我正在尝试构建一个包含一列数字的 DataTable 可排序表,但该列还包含文本 NA 以表示丢失的数据。我想知道如何编写自定义排序函数,以便当我对列进行排序时,NAs 出现在数字之后,而不是在列出从最大到最小的值之前。在这里写代码:https://codepen.io/mayagans/pen/VwKJeMo

$('#my-table').DataTable({
            "autoWidth": false,
            "order": []
        });
td {
  padding: 0 20px;
}

table {
  margin: 10px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<table id="my-table">
    <thead>
        <th>Nr. </th>
        <th>Name</th>
    </thead>
    <tr>
        <td>1</td>
        <td>Carl</td>
    </tr>
    <tr>
        <td>2</td>
        <td>Alan</td>
    </tr>
    <tr>
        <td>3</td>
        <td>Bobby</td>
    </tr>
      <tr>
        <td>NA</td>
        <td>Maya</td>
    </tr>
        <tr>
        <td>NA</td>
        <td>Jordan</td>
    </tr>
      </tr>
        <tr>
        <td>-</td>
        <td>Monica</td>
    </tr>
</table>

期望的输出:

从大到小排序时:

<table id="my-table">
    <thead>
        <th>Nr. </th>
        <th>Name</th>
    </thead>
    <tr>
        <td>3</td>
        <td>Bobby</td>
    </tr>
        <tr>
        <td>2</td>
        <td>Alan</td>
    </tr>
        <tr>
        <td>1</td>
        <td>Carl</td>
    </tr>
      <tr>
        <td>NA</td>
        <td>Maya</td>
    </tr>
        <tr>
        <td>NA</td>
        <td>Jordan</td>
    </tr>
      </tr>
        <tr>
        <td>-</td>
        <td>Monica</td>
    </tr>
</table>

任何帮助表示赞赏!

【问题讨论】:

    标签: javascript jquery datatable datatables-1.10


    【解决方案1】:

    您可以利用orthogonal data,它可以让您存储与显示值不同的自定义排序值:

    $('#my-table').DataTable( {
      columnDefs: [ { 
        targets: [ 0 ], 
        render: function ( data, type, row ) {
          if ( type === 'sort' ) {
            var sortValue = data;
            switch( data ) {
              case '-':
                sortValue = -999998;
                break;
              case 'NA':
                sortValue = -999999
                break;
              default: // already set, in this case
            } 
            return sortValue;
          } else { 
            return data;
          }
      }
      } ]
    } );
    

    这假定您的数值永远不会低于switch 语句中使用的两个值。如果您的整体数据与此不兼容,您可以根据需要进行调整。

    我的样本:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多