将字符串作为数字排序的数据表 [英] datatable sorting on string as number

查看:29
本文介绍了将字符串作为数字排序的数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数据表,我想按数字排序,它包含像 1st,2nd 之类的值....?

i have datatable and i want to sort in as numeric it contains value like 1st,2nd...., here is my code when i sort it it sorts values like 1st,10th,2nd so on how to sort it properly?

$('#example').DataTable( {
   //      "columnDefs": [
   //   { "visible": false, "targets": 4 }
   // ],
"aaSorting": [[1,'asc']],
   "columnDefs": [ {
    "targets": [2,5,6],
    "orderable": false
  } ,
  {
    "targets": 0,
    "orderable": false
  },
  { "width": "5%", "targets": 0 },
  { "width": "8%", "targets": 1 }],

  initComplete: function () {

    this.api().columns().every( function () {
      var column = this;
      var select = $('<select><option value=""></option></select>')
      .appendTo( $(column.footer()).empty() )
      .on( 'change', function () {
        var val = $.fn.dataTable.util.escapeRegex(
         $(this).val()
         );

        column
        .search( val ? '^'+val+'$' : '', true, false )
        .draw();
      } );

      column.data().unique().sort().each( function ( d, j ) {
        select.append( '<option value="'+d+'">'+d+'</option>' )
      } );
    } );
  }
}); 

推荐答案

我所知道的最简单的方法是使用 格式化数字插件

The simplest way I know of to do this is to use the Formatted Numbers plugin

jQuery.extend( jQuery.fn.dataTableExt.oSort, {
    "formatted-num-pre": function ( a ) {
        a = (a === "-" || a === "") ? 0 : a.replace( /[^d-.]/g, "" );
        return parseFloat( a );
    },
 
    "formatted-num-asc": function ( a, b ) {
        return a - b;
    },
 
    "formatted-num-desc": function ( a, b ) {
        return b - a;
    }
} );

$('#tbl_jaar').dataTable( {
     columnDefs: [
       { type: 'formatted-num', targets: 0 }
     ]
  } );

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css" rel="stylesheet"/>
<table id="tbl_jaar">
  <thead>
    <tr>
      <th>Places</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1st</td>
    </tr>
    <tr>
      <td>2nd</td>
    </tr>    
    <tr>
      <td>3rd</td>     
    </tr>   
    <tr>
      <td>4th</td>
    </tr>
    <tr>
      <td>5th</td>
    </tr>
    <tr>
      <td>6th</td>
    </tr>
    <tr>
      <td>7th</td>
    </tr>
    <tr>
      <td>8th</td>
    </tr>
    <tr>
      <td>9th</td>
    </tr>
    <tr>
      <td>10th</td>
    </tr>
  </tbody>
</table>

这篇关于将字符串作为数字排序的数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆