简体   繁体   中英

jquery datatables: how to shift columns mappings (because of inserted “row header column”)?

I have added "row header column" to my table (rendered by datatables jquery plugin):

在此处输入图片说明

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>

Data is accessed by ajax (send as an array, not as associative array).

The problem is that now I should re-arrange mappings for each column:

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

It is too verbose.

Is it possible to configure the same (map data column X to table column X+1 ) in one line? Just to say: "please, shift columns" or "please, remove first row-header-column form mappings".

Use columns and columns.data to specify array index for the data source. In this case, you would need to provide options for every column, including first one.

For example:

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

Alternatively, you could use combination of columnDefs.data and columnDefs.targets , but that is slightly more verbose.

So far the dynamic "default" configuration is the best found option:

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]... } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM