【问题标题】:Custom Sorting Capacities of jQuery dataTable ColumnjQuery dataTable 列的自定义排序能力
【发布时间】:2015-05-10 18:21:12
【问题描述】:

我有一个表,其中包含这样的容量列:

<table id="datatable" class="display" width="100%">
    <thead>
        <tr>
            <th>Col1</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>2 Go</td>
        </tr>
        <tr>
            <td>1 To</td>
        </tr>
        <tr>
            <td>320 Go</td>
        </tr>
        <tr>
            <td>2 To</td>
        </tr>
        <tr>
            <td>500 Go</td>
        </tr>
    </tbody>
</table>

我正在尝试使用 jQuery dataTable 对列进行排序以生成以下内容:

2 Go
320 Go
500 Go
1 To
2 To

但通过阅读排序和插件文档无法弄清楚如何做到这一点。

我尝试了this 解决方案,但无法成功。

【问题讨论】:

    标签: javascript sorting jquery-datatables


    【解决方案1】:

    使用您引用的代码的修改版本,我未经测试的建议是从您正在比较的数据中删除“Go”和“To”文本,同时将 100 万添加到以“To”结尾的数字'。

    注意:我使用了一百万,假设 NNN Go/To 永远不会 >= 一百万。

    jQuery.extend(jQuery.fn.dataTableExt.oSort, { “容量预”:函数(一){

    // Remove ' To' and add 1 million to the number:
    var x = String(a).replace(/ To/g, "1000000"); 
    
    // Just remove the text ' Go'
    x = String(a).replace(/ Go/g, "") 
    
    // now we are just returning a number to do your sorting comparisons against
    return parseFloat( x ); 
    

    },

    “容量-asc”:函数(a,b){ 返回 ((a b) ? 1 : 0)); },

    “容量描述”:函数(a,b){ 返回 ((a b) ? -1 : 0)); }

    然后在数据表中,将类型设置为容量

    $('table').dataTable({ "aoColumns": [{ "sType": "capacity" }], "aaSorting": [[ 0, "desc" ]], });

    【讨论】:

      【解决方案2】:

      你可以试试这个。希望你有 To and Go 作为选项。我使用 First char(T/G) 来获取 ascii 代码,并得到带有 num 第一部分的产品。

      jQuery.extend( jQuery.fn.dataTableExt.oSort, {
        "capacities-pre": function ( a ) {
            var x = a.substring(0, a.length - 2);
            var x_unit = (a.substring(a.length-2, a.length-1)).charCodeAt(0);
            return parseInt( x * x_unit, 10 );
        },
      
        "capacities-asc": function ( a, b ) {
          return ((a < b) ? -1 : ((a > b) ? 1 : 0));
        },
      
        "capacities-desc": function ( a, b ) {
          return ((a < b) ? 1 : ((a > b) ? -1 : 0));
        }
      } );
      

      【讨论】:

        猜你喜欢
        • 2013-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-08
        相关资源
        最近更新 更多