2012-09-13 2 views
1

I가 다음과 같은 HTML 테이블 :Datatables보기 : 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> 

거기에 어쨌든 배열보다 객체 배열을 반환하는 자바 스크립트 함수 fnGetData() 있나요 데이터 소스는 DOM 무엇입니까?

+0

. 동일한 클래스/텍스트 값을 가진 두 개의 헤더 셀이있는 경우 어떻게해야합니까? – Bergi

+0

흠 ... 잘 모르겠지만 첫 번째 값을 반환 할 것입니다. –

답변

1

그래서 조금 연구를했고 datatable 플러그인이 열을 처리하는 데별로 영리하지 않다는 것을 알았습니다. 그들은 항상 ar입니다. 광선은 정수로 액세스해야합니다. 열 및 속성을 처리하는 유일한 방법은 aoColumns object입니다. 초기화 후 해당 개체에 액세스하려면 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" 
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 's의보고 후 :

$(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')]); 
}); 

그러나 거기있다 더 나은 방법이 될 것입니다 ...

관련 문제