如何在html / css / js中创建折叠树表? [英] How to create a collapsing tree table in html/css/js?
问题描述
我有一些数据要显示,它们都是表格式和层次式的。我想让用户能够展开和折叠节点。
I have some data to display that is both tabular and hierarchical. I'd like to let the user be able to expand and collapse the nodes.
这样排序,除了功能:
http://www.maxdesign.com.au/articles/tree-table/
最好的方法是什么?我不会对使用现成的插件不利。
What would be the best way to approach this? I'm not adverse to using an off-the-shelf plugin.
推荐答案
SlickGrid has this functionality, see the tree demo.
如果您想自己创建,下面是一个示例( jsFiddle demo ):使用 data-depth
属性来构建你的表,以指示树中项的深度( levelX
CSS类只是用于样式缩进):
If you want to do build your own, here is an example (jsFiddle demo): Build your table with a data-depth
attribute to indicate the depth of the item in the tree (the levelX
CSS classes are just for styling indentation):
<table id="mytable">
<tr data-depth="0" class="collapse level0">
<td><span class="toggle collapse"></span>Item 1</td>
<td>123</td>
</tr>
<tr data-depth="1" class="collapse level1">
<td><span class="toggle"></span>Item 2</td>
<td>123</td>
</tr>
</table>
然后当点击切换链接时,使用Javascript隐藏所有< tr>
元素,直到找到等于或小于深度的< tr>
(排除已经折叠的那些):
Then when a toggle link is clicked, use Javascript to hide all <tr>
elements until a <tr>
of equal or less depth is found (excluding those already collapsed):
$(function() {
$('#mytable').on('click', '.toggle', function () {
//Gets all <tr>'s of greater depth below element in the table
var findChildren = function (tr) {
var depth = tr.data('depth');
return tr.nextUntil($('tr').filter(function () {
return $(this).data('depth') <= depth;
}));
};
var el = $(this);
var tr = el.closest('tr'); //Get <tr> parent of toggle button
var children = findChildren(tr);
//Remove already collapsed nodes from children so that we don't
//make them visible.
//(Confused? Remove this code and close Item 2, close Item 1
//then open Item 1 again, then you will understand)
var subnodes = children.filter('.expand');
subnodes.each(function () {
var subnode = $(this);
var subnodeChildren = findChildren(subnode);
children = children.not(subnodeChildren);
});
//Change icon and hide/show children
if (tr.hasClass('collapse')) {
tr.removeClass('collapse').addClass('expand');
children.hide();
} else {
tr.removeClass('expand').addClass('collapse');
children.show();
}
return children;
});
});
这篇关于如何在html / css / js中创建折叠树表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!