2012-09-13 65 views
1

现在,我有以下的HTML表:数据表:从DOM数据源通过名称引用列

<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> 

无论如何有一个JavaScript函数fnGetData()返回一个对象,而不是数组,当数据源是DOM?

+0

棘手。如果您有两个具有相同类/文本值的标题单元格,会发生什么情况? – Bergi

+0

嗯...我不确定,但我想它会返回第一个。 –

回答

1

所以,我研究了一下,发现datatable插件是不是在处理色谱柱非常聪明 - 他们总是AR射线需要用整数来访问。该处理的列及其属性的唯一的事情就是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" 
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

看着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')]); 
}); 

但必须有有更好的方式...