使用jquery数据表对长时间排序



我已经寻找了我的问题的答案,例如使用jQuery数据表排序时间列或自定义排序持续时间,但我没能找到一个适合我的问题。因此,我在这里。

我正在使用jquery Datables: https://datatables.net/来显示我当前项目中的表。我得到了包含持续时间的列的表,如:

99:39:25    
322:48:43
274:01:21
33:10:39

当我想把它们排序时,结果是不正确的:

99:39:25
33:10:39
322:48:43
274:01:21

我在文档中查找排序插件(https://datatables.net/plug-ins/sorting/),但没有帮助。我使用了自然时间排序,每次都得到上面的结果。有谁知道该怎么做吗?

这是我用来初始化我的HTML中的数据表:

<script>
$(document).ready(function() {
 $('.dataresults').DataTable({
   "iDisplayLength": 25,
   "searching": true,
   "pagingType": "simple",
   "order": [[7, "desc"]],
   "columnDefs": [{
     "type": 'time', "targets": [6,7]
   }],
 });
});
</script>

我找到了基于使用jQuery数据表的自定义排序持续时间的解决方案。我贴出了解决方案,如果有人会在我的情况下。

我替换了这个正则表达式:

/(?:(d+)m)?s*(?:(d+)s)?/

:

/(?:(d+):)?(?:(d+):)?(?:(d+):)?/

并按预期排序!

322:48:43
274:01:21
99:39:25
33:10:39

完整的脚本变成:

<script type="text/javascript">
$.extend(jQuery.fn.dataTableExt.oSort, {
"duration-pre": function (s) {        
    var duration;      
    s = s.toLowerCase();
    if(s === 'n/a'){ 
        duration = -1;           
    } else {            
        d = s.match(/(?:(d+):)?(?:(d+):)?(?:(d+):)?/);
        duration = parseInt(d[1] ? d[1] : 0) * 60 + parseInt(d[2] ? d[2] : 0) + parseInt(d[2] ? d[2] : 0) / 60;
    }
    return duration;
}
});
$(document).ready(function() {
$('.dataresults').DataTable({
  "iDisplayLength": 25,
  "searching": true,
  "pagingType": "simple",
  "order": [[7, "desc"]],
  "columnDefs": [{
    "type": 'duration', targets: [6,7]
  }],
});
});
</script>

最新更新