У меня есть несколько экземпляров DataTables на странице, и у большинства из них есть вложенная дочерняя таблица на строку (более подробная информация об этой строке).Дочерние таблицы не имеют точно такие же столбцы.Содержимое таблицы заполняется MySQL / PHP, поэтому таблицы уже существуют в HTML, когда этот код выполняется.
Я успешно скрываю два столбца в родительской таблице и щелкаю заголовок другого столбца, переключая их видимость.
Макет таблицы выглядит примерно так:
<table class='ic-table'>
<thead>
<tr>
<th></th> //Expanding details button for child table
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
<th>Col 4</th>
<th>Col 5</th>
<th>Col 6</th>
<th>Col 7</th>
<th>Col 8</th>
<th>Col 9</th>
<th></th> //Child table is this column
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<table class='ic-detail-table'>
<thead>
<tr>
<th></th>
<th>detail Col 1</th>
<th>detail Col 2</th>
<th>detail Col 3</th>
<th>detail Col 4</th>
<th>detail Col 5</th>
<th>detail Col 6</th>
<th>detail Col 7</th>
<th>detail Col 8</th>
<th>detail Col 9</th>
<th>detail Col 10</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
Использование:
var ic_tables = $('table.ic-table').each(function (i, obj) {
var cur_table = $(obj).DataTable({
paging: false,
autoWidth: false,
searching: false,
columnDefs: [
{"className": "dt-center", "targets": "_all"},
{ "visible": false, "targets": [7,8] }
],
ordering: false,
responsive: true,
dom: '<"clear">rt',
order: [[1, 'asc']]
});
cur_table.on('click', 'thead.summary-table-head th:nth-child(7)', function() {
// Get the column API object
var column1_hide = cur_table.column(7);
var column2_hide = cur_table.column(8);
// Toggle the visibility
column1_hide.visible( ! column1_hide.visible() );
column2_hide.visible( ! column2_hide.visible() );
});
});
Однако применение того же кода к моим дочерним таблицам не дает того же эффекта?
var ic_sub_tables = $('table.ic-detail-table').each(function (i, obj) {
var cur_detail_table = $(obj).DataTable({
paging: false,
autoWidth: false,
searching: false,
columnDefs: [
{"className": "dt-center", "targets": "_all"},
{ "visible": false, "targets": [8,9] } // CHANGED COLUMN TARGETS TO 8 + 9
],
ordering: false,
responsive: true,
dom: '<"clear">rt',
order: [[1, 'asc']]
});
cur_detail_table.on('click', 'thead.detail-table-head th:nth-child(8)', function() {
// Get the column API object
var detail_column1_hide = cur_detail_table.column(8);
var detail_column2_hide = cur_detail_table.column(9);
// Toggle the visibility
detail_column1_hide.visible( ! detail_column1_hide.visible() );
detail_column2_hide.visible( ! detail_column2_hide.visible() );
});