如何设置'目标'动态地在columnDefs dataTable.js中

时间:2015-03-26 09:50:09

标签: jquery datatables

我正在从dataTable数据生成xml。我想根据列名更改列可见性。我不想硬编码targets的值,如2或3,我也不想根据类名设置。

$(document).ready(function() {
   var dataOptions = {
    {
      "columnDefs": [ {
         "visible": false,
         "targets":2
     } ]
    }

   };
   $('#example').dataTable( dataOptions );
} );

#Edit
My XML DATA
  <root>
    <filterStartDate>2006-11-18</filterStartDate>
    <filterEndDate>2015-02-11</filterEndDate>
    <responseCount>0</responseCount>
    <responseCountFormatted></responseCountFormatted>
    <metadata>
     <columns>
        <column name="startDate" type="DATE" nameT="Start Date" sortable="true" />
        <column name="endDate" type="DATE" nameT="End Date" sortable="true" />
        <column name="COMPANY_ID" type="STRING" nameT="Company" sortable="true" />
        <column name="COMPANY_ID___code" type="STRING" nameT="Company" visible="false" />
        <column name="multipleGroupBy" type="STRING" nameT="Multiple Group By" visible="false" />
     </columns>
    </metadata>
    <pageInformation><totalPages>1</totalPages><totalRows>10</totalRows><pageStart>0</pageStart><pageEnd>10</pageEnd><rowsPerPage>50</rowsPerPage></pageInformation>
    <data>
       <row startDate="2006-11-18" endDate="2015-02-11" COMPANY_ID="CONSUMER" COMPANY_ID___code="CONSUMER" multipleGroupBy="|CONSUMER">
       </row>
    </data>
   </root>

我能以更好的方式实现这一目标吗?

2 个答案:

答案 0 :(得分:1)

直接向我看,就像XML是专门为dataTables生成的,或者是基于dataTables实例本身。当您编写&#34; 时,我想根据列名更改列可见性&#34;我想你的意思是列属性visible

var parser = new DOMParser(),
    doc = parser.parseFromString(xml, "application/xml"),
    columns = doc.querySelectorAll('column'),
    options = { columnDefs:[] },
    column;

for (var i=0;i<columns.length;i++) {
    column = columns[i];
    options.columnDefs.push({ 
        data : column.getAttribute('name'),
        title : column.getAttribute('nameT'),        
        type : column.getAttribute('type'),        
        visible : column.getAttribute('visible') == 'false' ? false : true,        
        sortable : column.getAttribute('sortable'),        
        targets : i
    });
}

var table = $('#example').DataTable(options);

演示 - &gt; http://jsfiddle.net/pbtb8h42/ 很抱歉,如果我误解了这个问题。

答案 1 :(得分:0)

您只需要动态更改i的值

定义 var i = 2; ,并将此 i 值分配给“ targets”:i ,然后更改我随你便