jQuery - 第三方表格插件DataTables使用详解15(行数据分组)
二十六、行数据分组
1,效果图
(1)表格默认将数据先按性别进行排序。
(2)当渲染完毕后,我们在相同性别的数据行上方插入一个分组头,从而将人员按性别分成两组显示。

2,样例代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="js/jquery-3.1.1.js" type="text/javascript"></script>
<script src="media/js/jquery.dataTables.js" type="text/javascript"></script>
<link rel="stylesheet" href="media/css/jquery.dataTables.css" type="text/css" />
<style media="screen">
tr.group, tr.group:hover {
background-color: #ddd !important;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
var table = $('#myTable').DataTable({
"ajax": 'data.txt',
"order": [[2,'desc']], //默认按3列(性别)数据降序排序
"drawCallback": function ( settings ) {
var api = this.api();
var rows = api.rows( {page:'current'} ).nodes();
var last=null;
//添加分组头
api.column(2, {page:'current'} ).data().each( function ( group, i ) {
if ( last !== group ) {
$(rows).eq( i ).before(
'<tr class="group"><td colspan="4">'+group+'</td></tr>'
);
last = group;
}
} );
}
});
});
</script>
</head>
<body>
<table id="myTable">
<thead>
<tr>
<th>编号</th>
<th>姓名</th>
<th>性别</th>
<th>出生日期</th>
</tr>
</thead>
</table>
</body>
</html>
3,数据文件
{
"data": [
[
"001",
"张三",
"男",
"2011-11-23"
],
[
"002",
"李四",
"女",
"2001-11-23"
],
[
"003",
"刘士元",
"男",
"2021-08-21"
],
[
"004",
"赵四",
"男",
"2008-08-08"
],
[
"005",
"赵五",
"女",
"2008-08-08"
],
[
"006",
"赵六",
"男",
"2008-08-08"
]
]
}
附:功能改进
既然我们按性别分组了,那么性别这一列自然可以给它隐藏掉(这个不影响数据的排序和分组)。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="js/jquery-3.1.1.js" type="text/javascript"></script>
<script src="media/js/jquery.dataTables.js" type="text/javascript"></script>
<link rel="stylesheet" href="media/css/jquery.dataTables.css" type="text/css" />
<style media="screen">
tr.group, tr.group:hover {
background-color: #ddd !important;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
var table = $('#myTable').DataTable({
"ajax": 'data.txt',
"columnDefs": [
{ "visible": false, "targets": 2 } //隐藏性别列
],
"order": [[2,'desc']], //默认按3列(性别)数据降序排序
"drawCallback": function ( settings ) {
var api = this.api();
var rows = api.rows( {page:'current'} ).nodes();
var last=null;
//添加分组头
api.column(2, {page:'current'} ).data().each( function ( group, i ) {
if ( last !== group ) {
$(rows).eq( i ).before(
'<tr class="group"><td colspan="4">'+group+'</td></tr>'
);
last = group;
}
} );
}
});
});
</script>
</head>
<body>
<table id="myTable">
<thead>
<tr>
<th>编号</th>
<th>姓名</th>
<th>性别</th>
<th>出生日期</th>
</tr>
</thead>
</table>
</body>
</html>
