我正在尝试创建一个带有可伸缩列的动态 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/