点击这里查看datatables官网介绍
点击这里查看datatables中文网介绍
效果如下图所示:
点击首列调用ajax返回数据,并展开明细行如下图所示:
CSS代码:
td.details-control {background: url('../../scripts/datatables-1.10.19/images/details_open.png') no-repeat center center;cursor: pointer;}tr.details td.details-control {background: url('../../scripts/datatables-1.10.19/images/details_close.png') no-repeat center center;}
HTML代码:
<table id="example" class="table table-striped table-over table-bordered" style="white-space: nowrap;width:100%;cursor:pointer" cellspacing="0"></table>
JS代码:
<script type="text/javascript">var dtsLanguage = "/Scripts/datatables-zh-cn/datatables_zh-cn.txt";var table;var url = "/Home/GetData";var detailRows = [];//用来记录显示明细行id的数组$(document).ready(function () {table = $('#example').DataTable({ajax: {url: url,type: "Get",dataType: "json",data: {},dataSrc: function (json) {return json;},error: function () {alert("服务器未正常响应,请重试");}},dom: 'Bfrtip',buttons:[{extend: 'pageLength',className: 'btn btn-primary',},],columns: [{className: 'details-control',orderable: false,data: null,defaultContent: '', },{ title: "Name", data: "Name"},{ title: "Position", data: "Position"},{ title: "Office", data: "Office"},],language: {url: dtsLanguage}});// 每次重绘,循环details数组显示所有子行table.on('draw', function () {$.each(detailRows, function (i, id) {$('#' + id + ' td.details-control').trigger('click');});});$('#example tbody').on('click', 'tr td.details-control', function () {var tr = $(this).closest('tr');var row = table.row(tr);var idx = $.inArray(tr.attr('id'), detailRows);if (row.child.isShown()) {tr.removeClass('details');row.child.hide();//从数组中移除detailRows.splice(idx, 1);}else {tr.addClass('details');row.child(format(row.data())).show();//增加到数组if (idx === -1) {detailRows.push(tr.attr('id'));}}});});function format(rowData) {var html;$.ajax({url: '/Home/Details',data: {name: rowData.Name},async: false,type: 'post',dataType: 'json',success: function (json) {var data = json.data[0];html = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +'<tr>' +'<td>Age:</td>' +'<td>' + data.Age + '</td>' +'</tr>' +'<tr>' +'<td>Salary:</td>' +'<td>' + data.Salary + '</td>' +'</tr>' +'<tr>' +'<td>Extra info:</td>' +'<td>And any further details here (images etc)...</td>' +'</tr>' +'</table>';}});return html;}</script>