2016-01-11 76 views
0
var oTable = $('#table').dataTable({ 
    "bJQueryUI": true, 
    "aaData": jsonList, 
    "bPaginate": true, 
    "aoColumns": [ 
     { 
      "mDataProp": null, 
      "sClass": "control center", 
      "sDefaultContent": '<img src="http://i.imgur.com/SD7Dz.png">' 
     }, 
     { "mDataProp": "ente" }, 
     { "mDataProp": "cup" }, 
     { "mDataProp": "decreto" }, 
     { "mDataProp": "data" }, 
     { "mDataProp": "importoImpegno" }, //this is a currency 
     { "mDataProp": "finanziato" }, //this is a currency 
     { "mDataProp": "importoPagato" }, //this is a currency 
     { "mDataProp": "importoInPagamento" } //this is a currency 
    ], 
    "aoColumnDefs": [ 
    { "sClass": "currency", "aTargets": [ 5, 6, 7, 8 ]} 
    ], 
    "oLanguage": { 
     "sInfo": "_TOTAL_ entries" 
    }, 
    "aaSorting": [[1, 'asc']] 
}); 

正如您所见,我只将.currency类添加到货币的列。 我需要格式化这些货币(例如3235到3.235,00),我已经有了这个功能。创建dataTable时设置货币格式

function currencyFormatIT(num) { 

    if(num != null && num != "") { 
     num = parseFloat(num); 
     num = num 
     .toFixed(2) 
     .replace(".", ",") 
     .replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1."); 
    } 
    else { 
     num = ""; 
    } 

    return num; 
} 

我试图用此方法,以便:

$("table.myTable > tbody td.currency").each(function(){ 
    $(this).html(currencyFormatIT($(this).html())); 
    $(this).css("text-align", "right"); 
}); 

但是,它的工作只出现在第一页的数据表行:

First page

从第二页开始:

Second page

如果我添加以下代码:

$(document).on("click", "td.currency", function(){ 
    alert($(this).html()); 
}); 

适用于所有网页上的所有TD!

1)为什么? 2)如果我要调用currencyFormatIT()函数类似的回调函数(也许在我创建数据表.dataTable({..代码我该怎么办?

回答

0

可以使用fnDrawCallback功能。

var oTable = $('#table').dataTable({ 

    "fnDrawCallback": function (oSettings) { 
     // Format Currency here 
    } 

} 

你可以检查documentation以获得更多关于可能的回调函数的细节:

+0

好的,但是我应该怎么传递给currencyFormatIT()函数呢?我该如何告诉他:“为每个类货币调用currencyFormatIT()”? – Dave

+0

Works但是现在每次都调用currencyFormatIT()我改变了页面或者对列进行了排序。这是不对的。有任何回调函数只被调用一次? – Dave

+0

@DavideFruci是不是你想要的?当您更改页面时,您需要为该页面上的新数据设置货币格式。但是如果你只想调用一次,你可以使用fnInitCallback函数。 –