【问题标题】:DataTables adding data-orderDataTables 添加数据顺序
【发布时间】:2018-08-07 05:52:25
【问题描述】:

我正在尝试通过在 createdCell 回调中添加数据顺序来对我的表进行排序 - 它工作正常,但之后似乎表缓存没有更新 - 按第一列排序(数据顺序中带有时间戳的日期)根本不起作用。 我试过table.rows/cells().invalidate() - 没有效果。

$.ajax({
            type: "POST",
            url: getLayoutData().urls.get_validation_history,
            data: {
                build_pk: build_pk,
                type: validation_type,
            },
            success: function(response){
                var response_data = JSON.parse(response);
                var table = $("#validationHistoryTable").DataTable({
                    data: response_data.snapshots,
                    destroy: true,
                    autoWidth: false,
                    columns: [
                        {data: 'updated'},
                        {data: 'updated_by'},
                        {data: 'type'},
                        {data: 'status'},
                        {data: 'comment'},
                    ],
                    columnDefs: [
                        {"width": "30%", "targets": 4},
                        {"targets": 0,
                         "createdCell": function(td, cellData, rowData, row, col){
                            raw = $(td).text().split(" ");
                            date = raw[0].split(".");
                            iso_time = date[2]+'-'+date[1]+'-'+date[0]+' '+raw[1];
                            $(td).attr('data-order', Date.parse(iso_time).getTime());
                         }
                        }
                    ],

【问题讨论】:

    标签: javascript sorting datatables


    【解决方案1】:

    您不能通过操作节点来插入正交数据。您可以通过节点和invalidate() 操作现有 和识别data-* 值,但不能作为DOM 节点后处理的一部分。查看 https://datatables.net/manual/data/orthogonal-datadata-* 值可以由

    指定
    • 标记
    • 指向备用 JSON 属性的呈现文字
    • 渲染回调

    在这个小例子中查看概念证明 -> http://jsfiddle.net/rtu0bjz6/

    {
      targets: 2,
      createdCell: function(td, cellData, rowData, row, col){
         counter++
         $(td).attr('data-order', counter)
      }   
    } 
    

    没有任何影响。该列按其原始数据排序,而不是其data-order。但是,如果您使用render() 函数并在type "sort" 上返回一个特殊值,那么它会按预期工作。

    {
      targets: 3,
      render: function ( data, type, row, meta ) {
        return type == 'sort' ? meta.row : data
      }
    }
    

    因此,在您的情况下,您可以执行类似(未测试)的操作:

    {
      targets: 0,
      render: function ( data, type, row, meta ) {
         if (type == 'sort') {
           var raw = data.split(" ");
           var date = raw[0].split(".");
           var iso_time = date[2]+'-'+date[1]+'-'+date[0]+' '+raw[1];
           return Date.parse(iso_time).getTime()
         } else {
           return data
         }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-01
      • 2011-10-08
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多