2012-09-13 39 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')]); 
}); 

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