如何在 html/css/js 中创建一个折叠树表? [英] How to create a collapsing tree table in html/css/js?

查看:66
本文介绍了如何在 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 隐藏所有 元素,直到找到一个相同或更小的 元素(不包括那些已经折叠的):

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆