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>

当数据源是 DOM 时,是否有一个 javascript 函数fnGetData()来返回对象而不是数组?

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

在查看了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 回答
1

因此,我进行了一些研究,发现该datatable插件在处理列方面不是很聪明——它们总是需要用整数访问的数组。唯一处理列及其属性的是aoColumns对象- 感谢@JustinWrobelfnSettings在初始化后找到访问该对象的方法。如果你没有这个,你就被困住了$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 回答