jquery datatables:如何移动列映射(因为插入了“行标题列”)?

问题描述 投票:1回答:2

我在表格中添加了“行标题列”(由datatables jquery插件呈现):

enter image description here

HTML:

<table id="main-table" class="table table-hover table-striped mainTable w-100">
    <thead>
        <tr>
            <th class="addNewHeader no-sort not-colvis">
                <a class="btn-sm" href="..." ><span class="material-icons">note_add</span></a>
            </th>
            <th>ID</th>
            <th>Part</th>
            <th>Released</th>
            <!-- other columns -->
        </tr>
    </thead>
    <tbody></tbody>
</table>

数据由ajax访问(作为数组发送,而不是作为关联数组发送)。

问题是现在我应该重新安排每列的映射:

table = $('#main-table').DataTable({
    ajax: {"url": "..."},
    columnDefs: [
    {
          targets: 1,
          render: function (data, type, row, meta) {
             return row[0]; // table column 1, data column 0
          }
     },
     {
            targets: 2,
            render: function (data, type, row, meta) {
               return row[1];  // table column 2, data column 1
            }
      },
      {
            targets: 3,
            render: function (data, type, row, meta) {
               return row[2];  // table column 3, data column 2
            }
      },
      // and so on
    ];
});

它太冗长了。

是否可以在一行中配置相同的(将数据列X映射到表列X + 1)?只是说:“请,移动列”或“请,删除第一行 - 标题 - 列格式映射”。

javascript html ajax datatables
2个回答
3
投票

使用columnscolumns.data指定数据源的数组索引。在这种情况下,您需要为每列提供选项,包括第一列。

例如:

table = $('#main-table').DataTable({
    ajax: {"url": "..."},
    columns: [
    {
          data: null
          render: function (data, type, row, meta) {
             // ... skipped ...
          }
     },
     { data: 1 },
     { data: 2 },
     { data: 3 },
     // ... skipped ...
    ];
});

或者,您可以使用columnDefs.datacolumnDefs.targets的组合,但这更加冗长。


1
投票

到目前为止,动态“默认”配置是最好的选择:

dataColumnCount = 15;
tableColumnCount = dataColumnCount + 1;
 dtOptions.columns = new Array(tableColumnCount );
 // default:
 for (i = 0; i < tableColumnCount; i++) {
     dtOptions.columns[i] = { targets: i, data: i - 1};
 };
 // replace where it is required with custom renderer:
 dtOptions.columns[0] = {
     render: function (data, type, row, meta) { ..} }
 dtOptions.columns[3] = {
     render: function (data, type, row, meta) { .. row[2]... } }
© www.soinside.com 2019 - 2024. All rights reserved.