javascript - 如何在 html/css/js 中创建折叠树表?

标签 javascript html css tree css-selectors

我有一些数据要显示,既有表格形式又有层次结构。我想让用户能够展开和折叠节点。

有点像这样,除了功能:

http://www.maxdesign.com.au/articles/tree-table/

处理此问题的最佳方法是什么?我并不反对使用现成的插件。

最佳答案

SlickGrid具有此功能,请参阅 tree demo .

如果您想构建自己的表格,这里有一个示例 (jsFiddle demo):使用 data-depth 构建您的表格属性以指示元素在树中的深度(levelX CSS 类仅用于样式缩进):

<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>发现深度相同或更小的深度(不包括已经折叠的):

$(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;
    });
});

关于javascript - 如何在 html/css/js 中创建折叠树表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5636375/

相关文章:

html - 网页 "Paper Notes effect"

javascript - 如何通过 IE 使用 JavaScript 导航到 URL?

javascript - 有没有办法通过 CSS 设置元素的加载?

javascript - AngularJS Bootstrap 下拉菜单在 IE 11 中不起作用

javascript - 如何制作只有 3 个字符和 3 个数字的正则表达式?

javascript - 使div在特定位置可拖动

html - 如何根据显示值更改行的背景颜色?

javascript - HttpClient 和 Rxjs

javascript - 这些错误是什么意思 getReadModeConfig, getReadModeRender, getReadModeExtract

javascript - 如何将 CSS 和 javascript 转换为类