最近项目中使用了DataTables,故小结了一下。
导入CSS文件
<link rel="stylesheet" href="<%=base %>/js/datatable/css/jquery.dataTables.min.css"/>
导入JS文件
<script type="text/javascript" src="<%=base %>/js/datatable/js/jquery.js"></script><script type="text/javascript" src="<%=base %>/js/datatable/js/jquery.dataTables.min.js"></script>
后台ajax请求:
var url = "getSj.do";
var dataTable;var options = { "bPaginate" : false, "bJQueryUI" : true, "processing" : true, "serverSide" : true, "bDestroy" : true, "bAutoWidth" : true, "sAjaxSource" : url, "columns" : [ { "title":'名称', "data" : "MC", "width" : "30%" }, { "title":'2010年', "data" : "20100000" }, { "title":'2009年', "data" : "20090000" }, { "title":'2008年', "data" : "20080000" }, { "title":'2007年', "data" : "20070000" } ], "oLanguage" : { "sProcessing" : "正在加载中...", "sLengthMenu" : "每页显示_MENU_条记录", "sZeroRecords" : "对不起,查询不到相关数据!", "sEmptyTable" : "表中无数据存在", "sInfo" : "当前显示_START_ ~ _END_条,共_TOTAL_条记录", "sInfoEmpty" : "当前显示0 ~ 0条,共0条记录", "sInfoFiltered" : "数据表中共为_MAX_条记录", "sSearch" : "搜索", "oPaginate" : { "sFirst" : "首页", "sPrevious" : "上一页", "sNext" : "下一页", "sLast" : "末页" } }};dataTable = $('#example').dataTable(options);
$('#example tbody').on('click','tr',function(){ if($(this).hasClass('selected')){ $(this).removeClass('selected'); }else{ dataTable.$('tr.selected').removeClass('selected'); $(this).addClass('selected'); } });或者是Ajax请求之后将数据赋给DataTables
var dataTablesOptions = {
"bPaginate" : false, "bJQueryUI" : true, "bFilter":false, "bDestroy" : true, "bAutoWidth" : true, "bSortClasses":false, "aoColumns" : [], "aaData":[], "oLanguage" : { "sProcessing" : "正在加载中...", "sLengthMenu" : "每页显示_MENU_条记录", "sZeroRecords" : "对不起,查询不到相关数据!", "sEmptyTable" : "表中无数据存在", "sInfo" : "当前显示_START_ ~ _END_条,共_TOTAL_条记录", "sInfoEmpty" : "当前显示0 ~ 0条,共0条记录", "sInfoFiltered" : "数据表中共为_MAX_条记录", "sSearch" : "搜索", "oPaginate" : { "sFirst" : "首页", "sPrevious" : "上一页", "sNext" : "下一页", "sLast" : "末页" } } };
var bgqs = "2012年@20120000,2011年@20110000,2010年@20100000,2009年@20090000";
var bgqArr = bggs.split(',');
var bgqMcArr = []; dataTablesOptions.aoColumns.push({ 'data':'id', 'title':'编号', "bVisible":false }); dataTablesOptions.aoColumns.push({ 'data':'Mc', 'title':'名称' }); for(var i = 0,len = bgqArr.length;i < len;i ++){ var bgqItemArr = bgqArr[i].split('@'); bgqMcArr.push(bgqItemArr[1]); dataTablesOptions.aoColumns.push({ 'data':bgqItemArr[0], 'title':bgqItemArr[1] }); } $.ajax({ url:'<%=base%>/getSj.do', type:'post', dataType:'json', success:function(ret){ dataTablesOptions.aaData = ret; dataTable = $('#indicateTableId').dataTable(dataTablesOptions); } });<table id="example" class="display" cellspacing="0" width="100%">
</table>