如何实现jQuery DataTable的多级子行展开功能?
jQuery DataTable 嵌套子行(子行的子行)实现示例
你需要的嵌套展开效果如下:
以下是完整可运行的实现示例:
HTML 结构
<table id="example" class="display" style="width:100%"> <thead> <tr> <th></th> <th>姓名</th> <th>职位</th> <th>办公室</th> <th>年龄</th> </tr> </thead> <tbody> <tr> <td></td> <td>Tiger Nixon</td> <td>System Architect</td> <td>Edinburgh</td> <td>61</td> </tr> <tr> <td></td> <td>Garrett Winters</td> <td>Accountant</td> <td>Tokyo</td> <td>63</td> </tr> </tbody> </table>
CSS 样式
/* 主行展开图标样式 */ table.dataTable tbody td.dtr-control { text-align:center; cursor: pointer; } table.dataTable tbody td.dtr-control:before { height:1em; width:1em; margin-top:-9px; display:inline-block; color:white; border:0.15em solid white; border-radius:1em; box-shadow:0 0 0.2em #444; box-sizing:content-box; text-align:center; text-indent:0 !important; font-family:Courier New; line-height:1em; content:"+"; background-color:#31b131; } table.dataTable tbody tr.parent td.dtr-control:before { content:"-"; background-color:#d33333; } /* 子行基础样式 */ .child-row { padding: 10px; background-color: #f5f5f5; } /* 子子行展开图标 */ .sub-dtr-control { cursor: pointer; display: inline-block; margin-right: 8px; } .sub-dtr-control:before { content:"+"; color: #31b131; font-weight: bold; } .sub-expanded .sub-dtr-control:before { content:"-"; color: #d33333; } /* 子子行内容容器 */ .sub-child-content { display: none; margin-left: 20px; margin-top: 8px; padding: 8px; background-color: #e8e8e8; }
JavaScript 逻辑
$(document).ready(function() { // 初始化DataTable实例 var table = $('#example').DataTable({ columnDefs: [ { className: 'dtr-control', orderable: false, targets: 0 } ], order: [[1, 'asc']] }); // 主行点击事件:控制子行展开/收起 $('#example tbody').on('click', 'td.dtr-control', function () { var tr = $(this).closest('tr'); var row = table.row(tr); if (row.child.isShown()) { // 收起子行 row.child.hide(); tr.removeClass('parent'); } else { // 渲染带子子行触发器的子行内容 row.child(createChildRow(row.data())).show(); tr.addClass('parent'); // 绑定子子行的展开/收起事件 $('.sub-dtr-control').on('click', function() { var parentDiv = $(this).closest('.child-row'); parentDiv.toggleClass('sub-expanded'); parentDiv.find('.sub-child-content').toggle(); }); } }); // 生成子行HTML内容的工具函数 function createChildRow(rowData) { return ` <div class="child-row"> <span class="sub-dtr-control"></span> <strong>${rowData[1]}的详细信息</strong> <div class="sub-child-content"> <p>邮箱:${rowData[1].toLowerCase().replace(' ', '.')}@example.com</p> <p>入职日期:2020-01-15</p> <p>部门:技术部</p> </div> </div> `; } });
核心实现要点
- 主行展开:借助DataTable内置的
row().child()方法,通过第一列的图标触发子行的显示/隐藏,并同步切换图标样式。 - 子子行展开:在子行的自定义HTML结构中添加独立的展开触发器,通过jQuery的
toggle()方法控制子子行内容的显示状态,同时切换图标样式。 - 层级区分:通过CSS设置不同层级行的背景色和缩进,让嵌套结构的视觉层级更清晰。
内容的提问来源于stack exchange,提问作者youllbehaunted
相关产品推荐
相关产品推荐

