3

DataTables jQuery プラグイン ( http://www.datatables.net ) を使用して、並べ替え可能なテーブルを作成しています。このプラグインは、各列のデータのデータ型を自動検出します。

列のデータ型を自分で指定したい場合は、データテーブルを初期化するときに「aoColumns」属性を追加します。

$('#accountTable').dataTable({
    "bPaginate": false,
    "sScrollX": "100%",
    "bScrollCollapse": true,
    "aoColumns": [
        null,
        null,
        { "sType": "currency" },
        { "sType": "currency" }
    ]
});

注意、datatables の通貨データ型プラグインをダウンロードしました。これはうまくいきます。

ただし、テーブルの列に変更を加えた場合、JS に戻ってそのテーブルで datatables プラグインを初期化する方法を変更するのを忘れてしまうのではないかと心配しています。

だから...必要に応じてテーブルに直接データ型を指定するのが理想的です:

<table class="dataTables display">
    <thead>
        <tr>
        <th>Category</th>
        <th>Product</th>
        <th sType="currency">Cost</th>
        <th sType="currency">Retail</th>
        ...

これを行う方法はありますか、DataTables のデフォルト機能 (これは見つかりません) を使用するか、JS ループまたは何かを使用してテーブルのタグをループし、「sType」属性が存在する sType を更新しますか?

4

4 に答える 4

2

これを行うための絶対にクールな方法を次に示します。

ヘッダー HTML:

<table id="sorted-table">
    <thead>
        <tr>
            <th data-s-type="string">Number</th>
            <th data-s-type="html">Complex Name</th>
            <th>Price</th>
            <th data-b-sortable="false">Action</th>
         </tr>
     </thead>
...

あなたのJS:

$('#sorted-table').dataTable({
   ...
   "aoColumns": $('#sorted-table').find('thead tr th').map(function(){return $(this).data()})
});

注: データ属性のこれらのダッシュは必要です。これらは jQuery によってキャメルケース形式に変換され、データ テーブル API と互換性があります。

于 2014-08-19T20:11:44.303 に答える
1

JS をループさせてヘッダーの属性をチェックすることはできますが、単にsType属性を作成して DOM に表示させることはできません。のような有効だが使用されていない属性を無効にする必要がありますheaders(スクリーン リーダーで問題が発生する可能性があります。より良いオプションがあるかもしれません)。

編集:

OK、CBroe のコメントを読んで、要素に任意の属性を与えること可能だと思います。

したがって、HTML5 に準拠したい場合は、プロパティdata-sTypeに名前を付けてから、次のようにすることができます。

var aoColumns = [];

$('#accountTable > th').each(function() {
   var sType = $(this).getAttribute("data-sType");
   aoColumns.push(sType ? sType : null);
});

$('#accountTable').dataTable({
   ...
   "aoColumns": aoColumns
});
于 2013-03-22T16:27:57.633 に答える
1

CBroe のコメントを取り上げると、これはまさに私がしていることです。HTML仕様data-ように、カスタム属性に接頭辞が付いていることを確認してください。data-stype='currency'

于 2013-03-22T16:37:35.690 に答える
1

助けてくれてありがとう!Russell Zahniser のコメントが機能するように、いくつかの調整を行う必要がありました。

  1. $('#accountTable > th') を $('#accountTable thead th') に変更しました
  2. aoColumns.push(sType ? sType : null) を aoColumns.push(sType ? { "sType" : "currency" } : null) に変更

最終結果:

var aoColumns = [];

$('#accountTable thead th').each(function() {
   var sType = $(this).getAttribute("data-sType");
   aoColumns.push(sType ? { "sType" : "currency" } : null);
});

$('#accountTable').dataTable({
   ...
   "aoColumns": aoColumns
});
于 2013-03-22T21:03:47.080 に答える