JQuery Datatables列呈现和排序

人气:832 发布:2022-10-16 标签: jquery javascript ajax datatables jquery-datatables

问题描述

我正在使用的DataTable包含一列YYYY-MM-DD HH:MM:SS格式的MySQL时间戳。我的表最初设置为按此列排序。Datatables会正确地自动检测时间戳格式并进行相应的排序。

我现在正在尝试更改此列的外观以使其更加用户友好,但不会影响它的排序方式。因此,我使用的columns.render功能如下:

{
        "data":"created_at",
        "name":"date",
        "visible":true,
        "title":"Date Created",
        "render": function(data, type, full, meta){
                var date = new Date(data);
                var options = {year: "numeric", month: "long", day: "numeric"};

                return date.toLocaleDateString('en-US', options);
        }
}

一旦我这样做,排序就不再正常工作。我的印象是render函数应该只影响数据的显示,但它仍然应该根据该行数据对象上的底层数据进行排序。这些是我尝试使用的文档(http://datatables.net/reference/option/columns.render)。

有人知道如何根据实际时间戳进行排序,同时显示更友好的日期吗?

推荐答案

我想我明白了。我只需要告诉呈现函数只对"Display"类型进行操作:

{
        "data":"created_at",
        "name":"date",
        "visible":true,
        "title":"Date Created",
        "render": function(data, type, full, meta){
                if(type == "display"){
                        var date = new Date(data);
                        var options = {year: "numeric", month: "long", day: "numeric"};

                        return date.toLocaleDateString('en-US', options);
                }

                return data;
        }
},

938