在使用 Datatables 插件时,如果你希望在点击某一行时关闭所有其他行的展开状态,可以通过以下步骤实现:
Datatables 是一个 jQuery 插件,用于增强 HTML 表格的功能,包括分页、即时搜索和多列排序等。它支持行展开和折叠功能,通常用于显示更多详细信息。
以下是一个示例代码,展示了如何在点击某一行时关闭所有其他行的展开状态:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Datatables Example</title>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
</head>
<body>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<!-- 表格数据 -->
</tbody>
</table>
<script>
$(document).ready(function() {
var table = $('#example').DataTable({
"responsive": true,
"columnDefs": [
{ "className": "dt-center", "targets": "_all" }
]
});
// 初始化行展开功能
$('#example tbody').on('click', 'tr', function () {
var tr = $(this).closest('tr');
var row = table.row(tr);
if (row.child.isShown()) {
// 如果当前行已经展开,则折叠它
row.child.hide();
tr.removeClass('shown');
} else {
// 折叠所有其他行
table.rows().every(function () {
if (this.child.isShown()) {
this.child.hide();
$('tr', this.node()).removeClass('shown');
}
});
// 展开当前行
row.child(format(row.data())).show();
tr.addClass('shown');
}
});
function format(d) {
// 自定义展开内容的格式
return '<div>详细信息: ' + d.name + '</div>';
}
});
</script>
</body>
</html>
$('#example').DataTable()
初始化表格。$('#example tbody').on('click', 'tr', function () {...})
监听行点击事件。row.child(format(row.data())).show()
展开当前行并显示自定义的详细信息。通过这种方式,你可以确保每次只有一行是展开状态,从而提高用户体验和数据的清晰度。
领取专属 10元无门槛券
手把手带您无忧上云