1

現在、次のhtmlテーブルがあります。

<table id="datatable">
    <thead>
        <th>fruits</th>
        <th>vegs</th>
    </thead>
    <tbody>
        <tr>
            <td>apple</td>
            <td>potato</td>
        </tr>
        <tr>
            <td>apple</td>
            <td>carrot</td>
        </tr>
    </tbody>
</table>

そして、次のように名前で列を参照したいと思います。

<script type="text/javascript">
$(document).ready(function() {  
    /* Init the table */
    var oTable = $('#datatable').dataTable( );

    //get by sTitle
    console.log(oTable);
    var row = oTable.fnGetData(1)
    console.log(row['vegs']);//should return 'carrot'
} );
</script>

fnGetData()データソースがDOMの場合、配列ではなくオブジェクトを返すjavascript関数を使用する方法はありますか?

4

3 に答える 3

2

これはテストされていませんが、動作する可能性があります:

$(function() {
    // Get an array of the column titles
    var colTitles = $.map($('#datatable th'), function() {
        return this.text();
    }).get();

    var oTable = $('#datatable').dataTable();

    var row = oTable.fnGetData(1);
    console.log(row[colTitles.indexOf('vegs')]);
});
于 2012-09-13T14:38:52.460 に答える
1

そのため、少し調べたところ、datatableプラグインは列の処理があまりスマートではないことがわかりました。列は常に整数でアクセスする必要がある配列です。列とそのプロパティを処理する唯一のものはaoColumnsオブジェクトfnSettingsです-初期化後にそのオブジェクトにアクセスする方法を見つけてくれた@JustinWrobelに感謝します。これを持っていない場合は、$table.find("thead th").

ただし、テーブルをオブジェクトの配列として簡単に取得できるようになりました。

var table = $mytable.dataTable(​…);
var cols = table.fnSettings().aoColumns,
    rows = table.fnGetData();

var result = $.map(rows, function(row) {
    var object = {};
    for (var i=row.length-1; i>=0; i--)
        // running backwards will overwrite a double property name with the first occurence
        object[cols[i].sTitle] = row[i]; // maybe use sName, if set
    return object;
});

result[1]["vegs"]; // "carrot"
于 2012-09-13T16:32:21.057 に答える
1

ShatyUTの答えとfbasを見た後、私はこれを思いつきました:

$(function() {
   var oTable = $('#datatable').dataTable( );
   var oSettings = oTable.fnSettings();  // you can find all sorts of goodies in the Settings

   var colTitles = $.map(oSettings.aoColumns, function(node) {
    return node.sTitle;
   });

   var row = oTable.fnGetData(1);
   console.log(row[colTitles.indexOf('vegs')]);
} );

しかし、もっと良い方法があるはずです...

于 2012-09-13T15:07:35.480 に答える