数据表排序数字无法正常工作

问题描述 投票:0回答:2

我在我的页面上使用数据表,它似乎工作正常,除了当你在数字字段上排序时,它以一种奇怪的方式排序,看看插图

enter image description here

还有这个

enter image description here

我已经尝试放置

 "aoColumns": [
            null,
            null,
            null,
            null,
            null,
            null,
            { "sType": 'numeric',
            "oCustomInfo":{
    "decimalPlaces":1,
    "decimalSeparator":"."}
            },
            null
        ]

但这似乎进一步扰乱了它的行为,因为它变得不可排序。你有线索吗?

谢谢

javascript jquery datatable datatables
2个回答
6
投票

您的问题是,由于某种原因,表数据被视为字符串而不是数字。检查值的格式。

如果例如你有这样的东西:

<table .....>
  <tbody>
    <tr>
      <td><span>1</span></td>
    </td>
    ....
  </tbody>
</table>

然后 Datatables 会将该列的值视为字符串而不是数字。如果您使用 asp .NET 等框架输出文本,这种情况很常见。

请参阅this了解类似问题


0
投票

经过几个小时的调试和跟踪后,我想我应该与其他人分享解决方案。

tldr:

columns:[{data: 'ttl_paid', "render":function(data,type,row,meta){if(type === 'sort' || type === 'type'){if(data != null){ return parseFloat(data);}else{return 0;}}else{if(data != null){ return '£'+data;}else{return '';}}}}]

定义列时,可以使用渲染函数。这用于预渲染数据。

渲染函数出于各种目的而运行,为此目的的两个关键函数是“类型”以确定列包含的数据类型和“排序”以对列进行排序。

所以解决办法就是在render函数中指定:

if(type === 'sort' || type === 'type'){
    //numeric for sorting & determining type
}else{
    //formatted for display
}

这样在加载时,数据表将其视为数字,并且在排序时对数字值进行排序。

这是格式良好的版本:

columns:[
    {
        data: 'ttl_paid', "render": function(data,type,row,meta){
            if(type === 'sort' || type === 'type'){
                if(data != null){
                    return parseFloat(data);
                }else{
                    return 0;
                }
            }else{
                if(data != null){
                    return '£'+data;
                }else{
                    return '';
                }
            }
        }
    }
]
© www.soinside.com 2019 - 2024. All rights reserved.