2015-10-16 121 views
0

在我的應用程序中,有一些列被授予特權。 如果沒有給出該列訪問該特定列的權限未顯示。jQuery DataTables中的動態列

我的代碼是這樣的:http://jsfiddle.net/oscar11/5jccbzdy/11/

// DataTable 
    var table = $('#example').DataTable({ 
     "order": [[0, 'asc']], 
     "drawCallback": function (settings){ 
      var api = this.api(); 

      // Zero-based index of the column containing names 
      var col_name = 0; 

      // If ordered by column containing names 
      if (api.order()[0][0] === col_name) { 
       var rows = api.rows({ page: 'current' }).nodes(); 
       var group_last = null; 

       api.column(col_name, { page: 'current' }).data().each(function (name, index){ 
        var group = name; 
        var data = api.row(rows[index]).data(); 

        if (group_last !== group) { 
         $(rows[index]).before(
          '<tr class="group" style="background-color:' + data[4] + '"><td colspan="5">' + group + '</td></tr>' 
         ); 

         group_last = group; 
        } 
       }); 
      } 
     } 
    }); 

如何使上面的代碼變得更具活力和調整被賦予特權的列數?

如果被賦予特權的列數:5,那麼:

'<tr class="group" style="background-color:' + data[4] + '"><td colspan="5">' + group + '</td></tr>' 

如果被賦予特權的列數:3,則:

'<tr class="group" style="background-color:' + data[2] + '"><td colspan="3">' + group + '</td></tr>' 

謝謝

回答

1

SOLUTION

您可以使用columns.name選項爲包含顏色的數據列定義名稱。

然後在行分組代碼中,您可以使用column-selectorcolor:name中的api.column("color:name").index()來獲取該列的索引。

使用下面的代碼:

// DataTable 
var table = $('#example').DataTable({ 
    "order": [[3, 'asc']], 
    "columnDefs": [ 
     { targets: 3, name: "group" }, 
     { targets: -1, name: "color" } 
    ], 
    "drawCallback": function (settings){ 
     var api = this.api(); 

     // Zero-based index of the column containing group names 
     var col_name = api.column("group:name").index(); 
     var col_color = api.column("color:name").index(); 

     // If ordered by column containing names 
     if (api.order()[0][0] === col_name) { 
      var rows = api.rows({ page: 'current' }).nodes(); 
      var group_last = null; 

      api.column(col_name, { page: 'current' }).data().each(function (group, index){ 
       if (group_last !== group){       
        var color = api.cell({ 
         row: api.row(rows[index]).index(), 
         column: col_color 
        }).data(); 

        $(rows[index]).before(
         '<tr class="group" style="background-color:' + color + '"><td colspan="5">' + group + '</td></tr>' 
        ); 

        group_last = group; 
       } 
      }); 
     } 
    } 
}); 

DEMO

this jsFiddle代碼和演示。

+0

謝謝你回答我的問題。我仍然困惑。我試過上面的代碼。我將列「渲染引擎」更改爲第三列。例如,列「引擎」沒有被賦予訪問權(如果沒有權限訪問該列將丟失)。我試過這樣的代碼:[link](http://jsfiddle.net/oscar11/5qtoyunq/1/)。 雖然其他列(列「引擎」)沒有被賦予訪問權限(被刪除),我怎樣才能使該分組列固定列「渲染引擎」? –

+0

@mosestoh,增加了更多細節並更新了示例。您可以在'columnDefs'部分指定包含組和顏色的列的索引。然後,'drawCalback'中的代碼將使用名稱'group'和'color'來檢索這些索引,而不是對它們進行硬編碼。 –

+0

謝謝你Gyrocode.com。但是我仍然很難實現我的問題。你嘗試看看這裏:[鏈接](http://jsfiddle.net/oscar11/5qtoyunq/1/)。儘管其他列(列「引擎」)沒有被賦予訪問權限(被刪除),我怎樣才能使該分組列固定列「渲染引擎」?我的意思是喜歡它。 –