gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:14:15 25 4
gpt4 key购买 nike

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

有点像这样,除了功能:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com