使用格式化数据进行渲染,在DataTables.net中使用原始数据进行排序

9

这是我的datatables配置示例

{
    "dom"        : "rltip",
    "processing" : true,
    "serverSide" : false,
    "order"      : [ [ 1 , "desc" ] ],
    "searching"  : false,
    data: [
       { "column-a" : "Sample Data A" , "column-b" : 10 , "column-c" : "Blah Blah" },
       { "column-a" : "Sample Data B" , "column-b" : 5 , "column-c" : "Blah Blah" },
       { "column-a" : "Sample Data C" , "column-b" : 38 , "column-c" : "Blah Blah" }
    ],
    "columnDefs" : [
        {
            "targets"   : 0,
            "orderable" : false,
            "data"      : "column-a"
        },
        {
            "targets"   : 1,
            "orderable" : false,
            "data"      : "column-b"
        },
        {
            "targets"   : 2,
            "orderable" : true,
            "className" : "title",
            "data"      : "column-c"
        }
     ]
}

我希望在显示数据时进行格式化,但在排序和其他后端相关的操作中,我想使用未经格式化的原始数据。
重要提示:我必须在客户端(JavaScript)上执行此操作。
我已经尝试了columnDefs上的render函数回调,但似乎不起作用。
"render" : function( data , type , row ) {

    if ( type === "sort" )
        return data;

    // format data here
    return data; // This is a formatted data

}

我所说的“似乎不起作用”是指排序出现了问题,它会考虑格式化后的数据,而不仅仅是原始数据。
我找到了这篇旧的相关文章,但它似乎不再适用于较新版本的datatables.net。

https://datatables.net/forums/discussion/8249/filtering-using-the-rendered-text-however-sorting-using-the-original-value

我正在使用版本1.10.15

1个回答

34

渲染函数type中被多次调用,每次使用不同的值。如果只将未格式化的数据设置为类型sort,则会错过其他与排序相关的类型,如type。相反,应该处理typedisplay的情况,并返回任何其他type值的未格式化数据。

"render" : function( data , type , row ) {    
    if ( type === "display" )
    {
       // format data here
       return data; // This is formatted data
    }    
    return data; // This is unformatted data    
}

2
我差点就做到了,谢谢你的帮助,它起作用了 :) - Jplus2
3
太棒了!这个解决方案为我节省了大量重构的工作。谢谢! - markzzz
3
这是应该添加到手册中的内容,因为软件的排序方法相当难以理解。 - Jason K.
哦,这刚刚救了我的一天。 - Johnathan Li

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接