Скрыть столбец в таблице со вложенными заголовками
Задача: скрывать необходимый столбец в таблице по нажатию соответствующего флажка. Если заголовок со вложенными столбцами, то нужно скрывать не каждый столбец по отдельности (их будет слишком много), а весь заголовок сразу со всеми вложениями.
Если можно скрывать и по отдельности - это будет круто. Дано: таблица, которая генерируется html-кодом в другой программе (поэтому динамически заполнять/удалять элементы не получится). Есть скрипт, который удаляет столбец с нужным индексом. Проблема в том, что таблица имеет вложенные заголовки и какие-то индексы совпадают, поэтому удаляется не то или лишнее. Если сделать обычные заголовки, то всё работает на отлично, а со вложенными какая-то беда. В js недолго копаюсь, всё больше на интуитивном уровне. Из того что нашла в интернете собрала то, что получилось ниже. Помогите, пожалуйста) Вот код скриптов $(function () { var $chk = $("#grpChkBoxStatistic input:checkbox"); var $tbl = $("#someTable"); var $tblhead = $("#someTable th"); $chk.prop('checked', true); $chk.click(function () { var colToHide = $tblhead.filter("." + $(this).attr("name")); var index = $(colToHide).index(); $tbl.find('tr :nth-child(' + (index + 1) + ')').toggle(); }); }); $(document).ready( function () { $('tbody tr').on('click', function (event) { $(this).closest("tr").siblings().removeClass("highlight"); $(this).toggleClass("highlight"); }); $("table").stickyTableHeaders(); } ); вот пример таблицы: <body> <div id="grpChkBoxStatistic"> <p><input type="checkbox" name="id1"> Имя</p> <p><input type="checkbox" name="id2"> Фамилия</p> <p><input type="checkbox" name="id3"> Коэффициенты</p> <p><input type="checkbox" name="id4"> Время регистрации</p> <p><input type="checkbox" name="id5"> Время отбытия</p> <p><input type="checkbox" name="id6"> Время прибытия</p> </div> <H2 ALIGN=CENTER>Таблица 1</H2> <div class="styleTable"> <TABLE BORDER=1 ALIGN=CENTER id="someTable"> <thead bgColor="white"> <TR> <th ROWSPAN=2 class="id1" style="display: table-cell;">Имя</th> <th ROWSPAN=2 class="id2" style="display: table-cell;">Фамилия</th> <th COLSPAN=3 class="id3" style="display: table-cell;">Коэффициенты</th> <th ROWSPAN=2 class="id4" style="display: table-cell;">Время регистрации</th> <th ROWSPAN=2 class="id5" style="display: table-cell;">Время отбытия</th> <th ROWSPAN=2 class="id6" style="display: table-cell;">Время прибытия</th> </TR> <TR> <th class="id7" style="display: table-cell;"><div class="vertical">К1</div></th> <th class="id8" style="display: table-cell;"><div class="vertical">К2</div></th> <th class="id9" style="display: table-cell;"><div class="vertical">К3</div></th> </TR> </thead> <tbody> <TR> <TD style="display: table-cell;">Евгений</TD> <TD style="display: table-cell;">Петров</TD> <TD style="display: table-cell;">2</TD> <TD style="display: table-cell;">3</TD> <TD style="display: table-cell;">4</TD> <TD style="display: table-cell;">00:00:00</TD> <TD style="display: table-cell;">16:48:51</TD> <TD style="display: table-cell;">00:00:13</TD> </TR> <TR> <TD style="display: table-cell;">Вася</TD> <TD style="display: table-cell;">Пупкин</TD> <TD style="display: table-cell;">0</TD> <TD style="display: table-cell;">0</TD> <TD style="display: table-cell;">0</TD> <TD style="display: table-cell;">00:00:13</TD> <TD style="display: table-cell;">16:49:04</TD> <TD style="display: table-cell;">00:00:51</TD> </TR> </tbody> </TABLE> </div> </body> |
Кроме колонки у вас есть еще строка. Надо добавить извилину, которая подумает "а если две строки, то что"
|
скрытие колонок таблицы
Arukueido, вариант для медитации ...
<!DOCTYPE HTML> <html> <head> <title>Untitled</title> <meta charset="utf-8"> <style type="text/css"> #grpChkBoxStatistic{ width: 200px; background-color: rgb(204, 153, 102); } #grpChkBoxStatistic label{ display: block; cursor: pointer; } </style> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script> $(function() { var $chk = $("#grpChkBoxStatistic"); var $tbl = $("#someTable"); var $thfist = $("thead tr:first th", $tbl); var $thlast = $("thead tr:last", $tbl); var $tbltr = $("tbody tr", $tbl); function findEl(parent, start, end) { var $elems = []; parent.each(function(indx, el) { var tds = $(">", el).slice(start, end); tds.each(function(i, el) { $elems.push(el) }) }); return $($elems) } var $one = 0, $two = 0; $thfist.each(function(indx, el) { var $c = this.colSpan, $r = this.rowSpan, $td = findEl($tbltr, $one,$one + $c), $text = $(el).text(), $th; $td = $td.add(el); $r == 1 && ($th = findEl($thlast, $two, $two + $c), $two += $c, $td = $td.add($th)); $one += $c; $('<label/>').append( $('<input/>', { type: 'checkbox', on : {click : function() { $td.toggle() }}, checked : true }) ).append($text).appendTo($chk); }) }); </script> </head> <body> <div id="grpChkBoxStatistic"></div> <H2 ALIGN=CENTER>Таблица 1</H2> <div class="styleTable"> <TABLE BORDER=1 ALIGN=CENTER id="someTable"> <thead bgColor="white"> <TR> <th ROWSPAN=2 class="id1" style="display: table-cell;">Имя</th> <th ROWSPAN=2 class="id2" style="display: table-cell;">Фамилия</th> <th COLSPAN=3 class="id3" style="display: table-cell;">Коэффициенты</th> <th ROWSPAN=2 class="id4" style="display: table-cell;">Время регистрации</th> <th ROWSPAN=2 class="id5" style="display: table-cell;">Время отбытия</th> <th ROWSPAN=2 class="id6" style="display: table-cell;">Время прибытия</th> <th COLSPAN=3 class="id3" style="display: table-cell;">Коэффициенты</th> <th ROWSPAN=2 class="id4" style="display: table-cell;">Время регистрации</th> <th ROWSPAN=2 class="id5" style="display: table-cell;">Время отбытия</th> <th ROWSPAN=2 class="id6" style="display: table-cell;">Время прибытия</th> </TR> <TR> <th class="id7" style="display: table-cell;"><div class="vertical">К1</div></th> <th class="id8" style="display: table-cell;"><div class="vertical">К2</div></th> <th class="id9" style="display: table-cell;"><div class="vertical">К3</div></th> <th class="id7" style="display: table-cell;"><div class="vertical">К4</div></th> <th class="id8" style="display: table-cell;"><div class="vertical">К5</div></th> <th class="id9" style="display: table-cell;"><div class="vertical">К6</div></th> </TR> </thead> <tbody> <TR> <TD style="display: table-cell;">Евгений</TD> <TD style="display: table-cell;">Петров</TD> <TD style="display: table-cell;">2</TD> <TD style="display: table-cell;">3</TD> <TD style="display: table-cell;">4</TD> <TD style="display: table-cell;">00:00:00</TD> <TD style="display: table-cell;">16:48:51</TD> <TD style="display: table-cell;">00:00:13</TD> <TD style="display: table-cell;">2</TD> <TD style="display: table-cell;">3</TD> <TD style="display: table-cell;">4</TD> <TD style="display: table-cell;">00:00:00</TD> <TD style="display: table-cell;">16:48:51</TD> <TD style="display: table-cell;">00:00:13</TD> </TR> <TR> <TD style="display: table-cell;">Вася</TD> <TD style="display: table-cell;">Пупкин</TD> <TD style="display: table-cell;">0</TD> <TD style="display: table-cell;">0</TD> <TD style="display: table-cell;">0</TD> <TD style="display: table-cell;">00:00:13</TD> <TD style="display: table-cell;">16:49:04</TD> <TD style="display: table-cell;">00:00:51</TD> <TD style="display: table-cell;">0</TD> <TD style="display: table-cell;">0</TD> <TD style="display: table-cell;">0</TD> <TD style="display: table-cell;">00:00:13</TD> <TD style="display: table-cell;">16:49:04</TD> <TD style="display: table-cell;">00:00:51</TD> </TR> </tbody> </TABLE> </div> </body> </html> |
Последний вариант просто красота. До того как посмотрела его сделала тупо, но работало: проверяла индекс и в зависимости от его значения убирала те или иные ячейки заголовка и таблицы.
Спасибо большое, буду сидеть разбираться что там в коде происходит) |
Часовой пояс GMT +3, время: 03:13. |