javascript - html高效可伸缩表格列

标签 javascript jquery css html-table

我正在尝试创建一个带有可伸缩列的动态 html 表格。 在实际情况中,每个标题可以有 20 列和最多 400 个值。 我想像这样呈现数据:

-----------------------------------------------------------
|    |            Header 1          | Header 2 | Header 3 |
-----------------------------------------------------------
|val1| col1.1 | col1.2 |...| col1.x | col 2.1  | col 3.1  |
-----------------------------------------------------------
|val2| col1.1 | col1.2 |...| col1.x | col 2.1  | col 3.1  |
-----------------------------------------------------------
 ...
-----------------------------------------------------------
|valx| col1.1 | col1.2 |...| col1.x | col 2.1  | col 3.1  |
-----------------------------------------------------------
|foot| foot1.1| foot1.2|...| foot1.x| foot2.1  | foot3.1  |
-----------------------------------------------------------

我希望能够单击 colx.1,展开或显示同一标题下的所有列,并折叠(或隐藏)其他标题的其他列。 在上表中单击任何 col2.1 单元格会将表更改为:

-----------------------------------------------------------
|    | Header 1 |            Header 2          | Header 3 |
-----------------------------------------------------------
|val1| col 1.1  | col2.1 | col2.2 |...| col2.x | col 3.1  |
-----------------------------------------------------------
|val2| col 1.1  | col2.1 | col2.2 |...| col2.x | col 3.1  |
-----------------------------------------------------------
 ...
-----------------------------------------------------------
|valx| col 1.1  | col2.1 | col2.2 |...| col2.x | col 3.1  |
-----------------------------------------------------------
|foot| foot1.1  | foot2.1| foot2.2|...| foot2.x| foot3.1  |
-----------------------------------------------------------

我试过做这样的事情: 在所有可以显示/隐藏的 td 元素上使用可隐藏类 和类似的东西:

var rows = $('tr');
rows.find('th:eq(1), td:eq(1)').on('click', function() {
    $('.hideable').toggle()
});

我还需要相应地更改页眉和页脚的 colspan

('th#foot1.1').attr('colspan',1)

上述解决方案有效,但效率很低,而且看起来不是很干净。

添加了简化的 jsFiddle 示例 jsfiddle.net/yrMsX .这个想法是不要同时扩展标题 1 和 2。

是否有更好、更有效的方法来实现这一点?

最佳答案

好的,我做了 this fiddle希望就是您要找的东西。

基本上你应该关注这个:

  • 给标题和它的子列相同的类
  • 为您想要切换的标题设置colspan属性
  • 为每个 header 设置一个data-fullcol 属性以跟踪它们的最大colspan
  • 绑定(bind)到点击事件仅绑定(bind)那些具有colspan属性的列
  • 为您希望保持可见的那些列提供第一
  • 在点击事件中隐藏所有列,其类不等于被点击的标题之一并且也不是第一个
  • 将所有其他 header colspan 设置为 1
  • 切换与您单击的标题具有相同类别的所有列
  • 切换标题的colspan,请将colspan设置为(data-fullcol - colspan +1)

注意:这仅在 header 具有单个类时才有效,如果您想给它们多个类,请考虑将“重要类”保存在特定属性中,例如 data-class

关于javascript - html高效可伸缩表格列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12659695/

相关文章:

javascript - 单击提交输入的单选按钮

javascript - 使用 jQuery 单击并拖动

javascript - CodeIgniter Controller 如何接受 ajax post

javascript - JQuery 使用 onclick() 将类添加到 $(this)

jquery - 如何使用 jQuery 获取 Bootsramp btn-group 的值

javascript - "id"如何使用 JSON 填充 jsTree

javascript - append 具有从 PHP 返回的特定 ID 的按钮不起作用

html - 使用 svg 路径和 raphael js 进行 3D 翻转

html - 使文本在重叠的 div 上方可见

css - 如何解决 Bootstrap 容器溢出问题?