通貨を保持する4つの列を持つデータテーブルがあります。現在、私はそれらを通常の列として扱い、各値に手動で「$」を追加しています。次に、列をカンマも含むようにフォーマットする必要があります。これを行うためのプラグインはありますか?'$'値の手動追加も削除したいと思います。いくつかのサイトをチェックしましたが、それらがどのように機能するのか本当に理解できませんでした。
3 に答える
[Updating answer to use DataTables 1.9+ and to honor rynop's better answer. Original answer preserved below the horizontal rule, but it's both out of date and less efficient than it should be.]
Since it is really the data that you want to modify, not the entire cell, you should be using the "render" property inside of the columns definition. To produce clean code, you could store the actual modification method elsewhere and just call over to it:
var myTable = $('#mytable').DataTable({
...
"columns": [
{
"data" : "key_of_column",
"render" : function( data, type, full ) {
// you could prepend a dollar sign before returning, or do it
// in the formatNumber method itself
return formatNumber(data);
}
}
]
...
});
// elsewhere... probably more likely in a utility namespace or module
function formatNumber(n) {
return n.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}
formatNumber
uses the regex from this accepted answer:
Add comma to numbers every three digits
[original answer]
I wouldn't add dollar values to each cell myself, a decision that has the side-effect of reducing the complexity of what you need to do. ;-) In any spreadsheet or table of currency values, you only need to put the currency symbol in the header or the first row. Putting it in the header will make your life easier, putting it in the first row will actually add complexity to your problem.
So, back to DataTables itself, you have multiple ways to skin this cat but here are two:
Render the whole table without the commas (ie. default DataTables behaviour) but adding a class to those particular cells with the sClass parameter. Then use fnDrawCallback to fire the comma-creating function as described in the above link.
Use only the regex from the above link to modify the cell as data comes in.
Something like this (where 3 is the zero-index column that you're modifying):
"aoColumnDefs": [ {
"aTargets": [3],
"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
var $currencyCell = $(nTd);
var commaValue = $currencyCell.text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
$currencyCell.text(commaValue);
}
}]
(aoColumnDefs
is part of your initialization object passed to dataTable()
);
If you absolutely MUST add the dollar sign, you would just prepend it in the same function before the text
function.
「aoColumns」で「mRender」メソッドを活用します。現在受け入れられているソリューションよりもクリーンで、おそらくより効率的です。
例:
oTable = $('#mytable').dataTable( {
...
"aoColumns": [
{
"sTitle": "MyCol With Number",
"mRender": function( data, type, full ) {
return formatNumber(data);
},
...
formatNumber は次のように定義されます。
function formatNumber(n) {
return n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
fnRender を使用すると、セルを完全に制御することもできます。たとえば、データを HTML でラップする場合などです。
完全な仕様については、 http://www.datatables.net/usage/columns#mRenderを参照してください