现在我有以下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()
来返回对象而不是数组?
答案 0 :(得分: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')]);
});
答案 1 :(得分:1)
$(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')]);
} );
但必须有更好的方法......
答案 2 :(得分:1)
所以,我研究了一下,发现datatable
插件在处理列时不是很聪明 - 它们总是需要用整数访问的数组。唯一处理列及其属性的是aoColumns
object - 感谢@JustinWrobel在初始化后找到fnSettings
方法来访问该对象。如果你没有这个,你就被$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"