什么是Datatable ?
Datatables是一款jquery表格插件。它是一个高度灵活的工具,可以将任何HTML表格添加高级的交互功能。
- 分页,即时搜索和排序
- 几乎支持任何数据源:DOM, javascript, Ajax 和 服务器处理
- 支持不同主题 DataTables, jQuery UI, Bootstrap, Foundation
- 各式各样的扩展: Editor, TableTools, FixedColumns ……
- 丰富多样的option和强大的API
- 支持国际化
- 超过2900+个单元测试
使用Datatable首先引入文件(css、js),可以去官方下载
<script src="${ctx}/components/plugin/datatables/1.10.10/media/js/jquery.dataTables.js"></script>
<link rel="stylesheet" type="text/css" href="${ctx}/components/plugin/datatables/1.10.10/media/css/jquery.dataTables.css"/>
注意:提前应该引入jquery.js
初始化Datatable
<table id="question" class="hover row-border dataTable no-footer" style="width:100%; ">
<thead>
<tr>
<th style="width: 5%;">*</th>
<th style="width: 30%;">标题</th>
<th style="width: 8%;">发布人</th>
<th style="width: 15%;">发布时间</th>
<th style="width: 13%;">是否有最佳标识</th>
<th style="width: 9%;">所属标签</th>
<th style="width: 8%;">回答数</th>
<th style="width: 12%;">操作</th>
</tr>
</thead>
</table>
Var question = $('#question').DataTable({
"serverSide": true,
"bLengthChange": false,
"ordering": false,
"deferRender": true,
"info": false,
"bAutoWidth": true,
"searching": false,
"paging": true,
"iDisplayLength": 15,
"pagingType": "full_numbers",
/* "scrollY": "400px", */
"scrollCollapse": true,
oLanguage: {
sProcessing: "处理中...",
sLengthMenu: "显示 _MENU_ 项结果",
sZeroRecords: "没有匹配结果",
sInfo: "显示第 _START_ 至 _END_ 项结果,共 _TOTAL_ 项",
sInfoEmpty: "显示第 0 至 0 项结果,共 0 项",
sInfoFiltered: "(由 _MAX_ 项结果过滤)",
sInfoPostFix: "",
sSearch: "搜索: ",
sUrl: "",
sEmptyTable: "表中数据为空",
sLoadingRecords: "载入中...",
sInfoThousands: ",",
oPaginate: {
sFirst: "首页",
sPrevious: "上页",
sNext: "下页",
sLast: "末页"
},
oAria: {
sSortAscending: "以升序排列此列",
sSortDescending: "以降序排列此列"
}
},
columns: [
{data: "id"},
{data: "F_desc"},
{data: "z_perna"},
{data: "F_PUBLISH_TIME"},
{data: "F_FINE"},
{data: "F_NAME"},
{data: "countans",
createdCell: function (td, cellData, rowData, row, col) {
$(td).css("text-align","center");
}},
{data: "F_desc",
createdCell: function (td, cellData, rowData, row, col) {
$(td).html(objString);
} }
] ,
ajax:{
url: "${ctx}/getQuestions",
type: "GET",
async : false,
dataType : 'json',
data:function(d){
d= getSelectInfo(d);
},
dataFilter: function (json) {//json是服务器端返回的数据
return json;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
},
fnDrawCallback:function(){
var api =this.api();
var startIndex= api.context[0]._iDisplayStart; //获取到本页开始的条数
api.column(0).nodes().each(function(cell, i) {
cell.innerHTML = startIndex + i + 1;
});
}
});
设置datatable行的选中效果
$('#question tbody').on('click','tr',function(){
//选中列表,只可单选
question.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
})
选中哪行的数据
var title = question.row('.selected').data().F_desc;
找到datatable选中行的数据
刷新Datatable
question.ajax.reload();