How to create a collapsing tree table in html/css/js?(如何在 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.
有点像这样,除了功能性:
Sort of like this, except functional:
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 有这个功能,请参阅 树演示.
SlickGrid has this functionality, see the tree demo.
如果你想自己构建,这里有一个例子(jsFiddle demo):构建您的表格带有 data-depth
属性以指示树中项目的深度(levelX
CSS 类仅用于样式缩进):
If you want to 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 中创建折叠树表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!