jquery datatable的详细用法
1,首先需要引用下面兩個文件
? ? ?
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" /><script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>?
2,DataTable支持的數據類型
https://www.datatables.net/manual/data/
2.1?數組
vardata = [["Tiger Nixon","System Architect","Edinburgh","5421","2011/04/25","$3,120"],["Garrett Winters","Director","Edinburgh","8422","2011/07/25","$5,300"] ]?2.2 對象?
[{"name": "Tiger Nixon","position": "System Architect","salary": "$3,120","start_date": "2011/04/25","office": "Edinburgh","extn": "5421"},{"name": "Garrett Winters","position": "Director","salary": "$5,300","start_date": "2011/07/25","office": "Edinburgh","extn": "8422"} ]2.3?自定義實例(本質和2.2一樣)?
functionEmployee ( name, position, salary, office ) {this.name = name;this.position = position;this.salary = salary;this._office = office;this.office = function() {returnthis._office;} }; $('#example').DataTable( {data: [newEmployee( "Tiger Nixon", "System Architect", "$3,120", "Edinburgh"),newEmployee( "Garrett Winters", "Director", "$5,300", "Edinburgh")],columns: [{ data: 'name'},{ data: 'salary'},{ data: 'office'},{ data: 'position'}] } );2.4 datatable的數據來源
1)DOM
如果沒有指定data,ajax選項,則DataTable會將當前table的html標簽上內容轉換成對應的數據(Array數據形式)。
2)Html5
Data-* 標簽上可以指定不同的值,用于排序和查找,td內部標簽的值對應當前單元格的數據。
<td data-search="21st November 2016 21/11/2016" data-order="1479686400">21st November 2016 </td>? 3)javascript
? 通過data配置,指定數據源。可以通過DataTables API row.add() row().remove()操作行數據。
? ? 4)Ajax?
? 通過服務器端分頁的方式,取得數據。返回的數據只能是json數組或對象(上面的2.1和2.2).?
3,有兩種分頁方式
3.1 客戶端分頁?
這種方式,代碼最簡單,整個數據量在10000條以內可以考慮。假設已經有了下面的table:?
<table id="table1" class="table table-condensed"><thead><tr><th>ID</th><th>Name</th><th>Score</th></tr></thead><tbody><tr><td>001</td><td>zhang</td><td>98</td></tr><tr><td>002</td><td>wang</td><td>99</td></tr></tbody> </table>?簡單調用一句話(使用默認設置),就可以使table具有排序,查找,分頁的基本功能。
?
$(function () { $("#table1").DataTable({ }); });?
3.2 服務器端分頁
這種方式針對大數據量的table(10萬條以上),每次只讀取當前的一頁數據,分頁在后臺做。代碼相對復雜,不過頁面響應更快,
服務器端的分頁一般要求我們先定義thead表頭,tbody可以不寫。
4,配置參數
這些配置參數可以通過javascript進行設置,也可以直接用HTML5標簽data-* 的方式寫在table的標簽中。
所有的配置選項:https://www.datatables.net/reference/option/
$(function () {$("#table1").DataTable({// 是否允許檢索"searching": false,// 是否允許排序"ordering": true,// 初期排序列//"order": [[0,'asc'],[1,'desc']],// 是否顯示情報 就是"當前顯示1/100記錄"這個信息"info": false,// 是否允許翻頁,設成false,翻頁按鈕不顯示"paging": false,// 水平滾動條"scrollX": false,// 垂直滾動條"scrollY": false,// 件數選擇功能 默認true"lengthChange": false,// 件數選擇下拉框內容"lengthMenu": [10, 25, 50, 75, 100],// 每頁的初期件數 用戶可以操作lengthMenu上的值覆蓋"pageLength": 50,//翻頁按鈕樣式// numbers:數字// simple:前一頁,后一頁// simple_numbers:前一頁,后一頁,數字// full:第一頁,前一頁,后一頁,最后頁//full_numbers:第一頁,前一頁,后一頁,最后頁,數字//first_last_numbers:第一頁,最后頁,數字"pagingType": "full_numbers",// 行樣式應用 指定多個的話,第一行tr的class為strip1,第二行為strip2,第三行為strip3.// 第四行以后又開始從strip1循環。。。 如果想指定成斑馬條狀,這里的class必須指定為2個。"stripeClasses": ['strip1', 'strip2', 'strip3'],// 自動列寬"autoWidth": true,// 是否表示 "processing" 加載中的信息,這個信息可以修改"processing": true,// 每次創建是否銷毀以前的DataTable,默認false"destroy": false,// 控制表格各種信息的表示位置(比較復雜) 默認:lfrtip// 具體參考:https://datatables.net/reference/option/dom"dom": 'lrtip',"language": {"processing": "DataTables is currently busy",// 當前頁顯示多少條"lengthMenu": "Display _MENU_ records",// _START_(當前頁的第一條的序號) ,_END_(當前頁的最后一條的序號),_TOTAL_(篩選后的總件數),// _MAX_(總件數),_PAGE_(當前頁號),_PAGES_(總頁數)"info": "Showing page _PAGE_ of _PAGES_",// 沒有數據的顯示(可選),如果沒指定,會用zeroRecords的內容"emptyTable": "No data available in table",// 篩選后,沒有數據的表示信息,注意emptyTable優先級更高"zeroRecords": "No records to display",// 千分位的符號,只對顯示有效,默認就是"," 一般不要改寫//"thousands": "'",// 小數點位的符號,對輸入解析有影響,默認就是"." 一般不要改寫//"decimal": "-",// 翻頁按鈕文字控制"paginate": {"first": "First page","last": "Last page","next": "Next page","previous": "Previous page"},// Client-Side用,Server-Side不用這個屬性"loadingRecords": "Please wait - loading..."},// 默認是false// 如果設為true,將只渲染當前也的html,速度會很快,但是通過API就訪問不到所有頁的數據,有利有弊//"deferRender": false,// 服務器端處理方式"serverSide": true,// ajax選項 可以直接簡單指定成請求的文件//"ajax": "data.json",// 也可以用對象來配置,更加靈活"ajax": {// url可以直接指定遠程的json文件,或是MVC的請求地址 /Controller/Actionurl: "data.json",type: 'POST',// 傳給服務器的數據,可以添加我們自己的查詢參數data: function (param) {param.opportunityNO = $('#txtSearch').val();return param;},//用于處理服務器端返回的數據。 dataSrc是DataTable特有的dataSrc: function (myJson) {if (myJson.timeout) {return "";}return myJson;}},//指定用于行ID的屬性名 默認是:DT_RowId"rowId": 'staffId',// 列定義"columns": [ {// data 可以是屬性名,或嵌套屬性(WORKTM1.ID),數組ArrOne[,] 用中括號中的字符連接數組后返回。"data": "WORKTM1",// 這里的class會應用到td上面"className": "dt-body-right",// 列寬"width": 40,// 很靈活,描繪每個單元格// data:當前cell的data,這個data和type有關// type:filter,display,type,sort// row:當前行數據// https://datatables.net/reference/option/columns.render"render": function (data, type, row, meta) {return type === 'display' && data.length > 40 ?'<span title="' + data + '">' + data.substr(0, 38) + '...</span>' : data;},// 是否可排序 默認值:true"orderable": true,// 指定當前列排序操作的時候,用哪一列(幾列)的數據進行真正的排序(通常是隱藏的)"orderData": [0, 1],// 這個屬性 和type屬性相似,指定排序時候這一列該怎么轉換數據,//需要用到其他的插件 詳細: https://datatables.net/plug-ins/sorting/"orderDataType": "dom-text",// 是否顯示當前列 默認值:true"visible": false,// 是否允許搜索此列 默認值:true"searchable": false,//這個屬性僅Client-Side有效, Server-Side在服務器端排序 //主要用于排序和篩選,指定當前列作為什么類型進行解析//內置值:date,num,num-fmt,html-num,html-num-fmt,html,string// 還可以用其他插件提供的類型 :詳細: https://datatables.net/plug-ins/sorting/// 有html開頭的,都會講html標簽先移除后進行數據處理"type": "html",// 列頭文字,如果沒有指定thead,則會生成。如何指定了thead,則會覆蓋當前列頭文字"title": "My column title",// defaultContent:默認值,屬性值為null或undefined就會用這個值"defaultContent": "<i>Not set</i>",// 單元格類型:"th","td""cellType" : "td",// 單元格創建完后的回調,可以作為render的補充// cell:TD的dom// cellData:原始的單元格數據,如何render中進行了格式化,用$(cell).html()來取格式化后的數據// rowData:行數據// row:行號// col:列號"createdCell": function (cell, cellData, rowData, row, col) {if ( cellData < 1 ) {$(td).css('color', 'red')}}},{ "data": "WORKTM2", "className": "dt-body-right", "width": 40 },{ "data": "WORKTM3", "className": "dt-body-right", "width": 40 },{ "data": "WORKTM4", "className": "dt-body-right", "width": 40 },{ "data": "RESTDAY1", "className": "dt-body-right", "width": 40 },{ "data": "RESTDAY2", "className": "dt-body-right", "width": 40 },{ "data": "RESTDAY3", "className": "dt-body-right", "width": 40 },{ "data": "RESTDAY4", "className": "dt-body-right", "width": 40 },{ "data": "RESTDAY5", "className": "dt-body-right", "width": 40 }],// 和上面的columns類似,columns可以定義的屬性,都可以在這里定義,// 另外增加targets屬性用于指定列范圍(可以多列)// 優先級:上面的columns高于columnDefscolumnDefs: [{targets: [0, 2],render: function (data, type, row, meta) {if (type === 'display') {var ctemp = $(".dayinfo").children().eq(meta.col).attr("class");var cname = ctemp ? ctemp : "";var readonly = $(".dayinfo").children().eq(meta.col).attr("data-fixed") == "fixed" ? "readonly" : "";return '<input type="input" class="form-control dt-body-center ' + cname + '" ' + readonly + ' value="' + data + '">';}return data;},}],// 每一行創建完調用的函數"createdRow": function (row, data, dataIndex) {// row : tr dom// data: row data// dataIndex:row data's indexif (data[4] == "A") {$(row).addClass('important');}},// 每一行被創建,但還沒有被加載到document中,這個函數優先于createdRow// 個人覺得用createdRow更好"rowCallback": function (row, data, index) {// row : tr dom// data: row data// index:row data's indexif ( data[4] == "A" ) {$('td:eq(4)', row).html( '<b>A</b>' );}},//thead被描畫后調用"headerCallback": function (thead, data, start, end, display) {//thead:dom, data:原始的datatable數據,display:當前顯示排序好的datatable數據(有可能經過排序)// start end :當前dispaly數據的開始結束序號$(thead).find('th').eq(0).html( 'Displaying '+(end-start)+' records' );},// tfoot被描畫后調用,通常可用于計算合計值"footerCallback": function (tfoot, data, start, end, display) {//tfoot:dom, data:原始的datatable數據,display:當前顯示排序好的datatable數據(有可能經過排序)// start end :當前dispaly數據的開始結束序號var api = this.api();$( api.column( 5 ).footer() ).html(api.column( 5 ).data().reduce( function ( a, b ) {return a + b;}, 0 ));},// 初始化,描畫都已經完成,常用于ajax"initComplete": function( settings, json ) {$('div.loading').remove();},// 每次DataTable描畫后都要調用,調用這個函數時,table可能沒有描畫完成,// 所以不要在里面操作table的dom,要操作dom應放在initComplete"drawCallback": function( settings ) {var api = this.api();// Output the data for the visible rows to the browser's consoleconsole.log( api.rows( {page:'current'} ).data() );},// 這個函數可以改寫數字的格式化方式// 默認DataTable用 language.thousands來解析數字,“,”"formatNumber": function ( toFormat ) {return toFormat.toString().replace(/\B(?=(\d{3})+(?!\d))/g, "'");}});});5,服務器端的參數
// 發送到服務器端的數據// draw:計數器,返回數據的時候用這個值設定// start:開始記錄(0 besed index)// length:每頁條數// search[value]:檢索文字// order[i][column]:int 排序列的序號 例如:2,代表第3列排序 i代表有幾個排序,一個的話服務器端這樣寫“order[0][column]”// order[i][dir]:排序的方式"desc","asc"// 下面comuns中的i取值從0~columns.length,所有的columns信息都發送到了服務器// columns[i][data]:columns上定義的data屬性值// columns[i][name]:columns上定義的name屬性值// columns[i][searchable]:列能不能檢索// columns[i][orderable]:列能不能排序// columns[i][search][value]:列的檢索值 string// 服務器返回的數據// draw:和Request的draw設定成一樣的值// recordsTotal:所有的總件數// recordsFiltered:篩選后的總件數// data:返回的數據// 每一行數據上面,可以包含這幾個可選項// DT_RowId:加在行上的ID值// DT_RowClass:加在行上的Class// DT_RowData:加在行上的額外數據(object)// DT_RowAttr:加在行上的屬性(object)// error:如果有錯誤,就設定這個值,沒有錯誤,不要包含這個值例子:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Configuration; using AppBlock; using System.Data.SqlClient; using Newtonsoft.Json;namespace alfest.Ajax {public partial class Category : System.Web.UI.Page{string mode, option, user, limit, start, searchKey, orderByColumn, orderByDir, estMstSrno, pnlsrno, draw, jsonString;CommonClass cmnCls = new CommonClass();protected void Page_Load(object sender, EventArgs e){mode = Request.QueryString["mode"] == null ? "" : Request.QueryString["mode"].ToString();option = Request.QueryString["option"] == null ? "" : Request.QueryString["option"].ToString();limit = Request.QueryString["length"] == null ? "" : Request.QueryString["length"].ToString();start = Request.QueryString["start"] == null ? "" : Request.QueryString["start"].ToString();user = Request.QueryString["user"] == null ? "" : Request.QueryString["user"].ToString();searchKey = Request.QueryString["search[value]"] == null ? "" : Request.QueryString["search[value]"].ToString();orderByColumn = Request.QueryString["order[0][column]"] == null ? "" : Request.QueryString["order[0][column]"].ToString();orderByDir = Request.QueryString["order[0][dir]"] == null ? "" : Request.QueryString["order[0][dir]"].ToString();estMstSrno = Request.QueryString["estMstSrno"] == null ? "" : Request.QueryString["estMstSrno"].ToString();pnlsrno = Request.QueryString["pnlsrno"] == null ? "" : Request.QueryString["pnlsrno"].ToString();draw = Request.QueryString["draw"] == null ? "" : Request.QueryString["draw"].ToString();if (option == "GetAllAdminCategory"){// Cls_Category CatgObj = new Cls_Category();// CatgObj.orderColumn = Convert.ToInt32(orderByColumn);// CatgObj.limit = Convert.ToInt32(limit);// CatgObj.orderDir = orderByDir;// CatgObj.start = Convert.ToInt32(start);// CatgObj.searchKey = searchKey;// CatgObj.option = "GetAllAdminCategory";// or user your own method to get data (just fill the dataset)// DataSet ds = cmnCls.PRC_category(CatgObj);dynamic newtonresult = new{status = "success",draw = Convert.ToInt32(draw == "" ? "0" : draw),recordsTotal = ds.Tables[1].Rows[0][0],recordsFiltered = ds.Tables[1].Rows[0][0],data = ds.Tables[0]};jsonString = JsonConvert.SerializeObject(newtonresult);Response.Clear();Response.ContentType = "application/json";Response.Write(jsonString);}}} }6,DataTable常用事件?
//常用事件// init:初始化和數據都加載完成,和 initComplete配置等價$('#example').on('init.dt', function () {console.log('Table initialisation complete: ' + new Date().getTime());}).dataTable();// error:處理數據出錯 errMode必須為“none”,才會觸發error事件$.fn.dataTable.ext.errMode = 'none'; // alert,throw,none, a function$('#example').on('error.dt', function (e, settings, techNote, message) {console.log('An error has been reported by DataTables: ', message);}).DataTable();// xhr:ajax加載數據完成后調用,這時數據并沒有被描畫,等價于 ajax.dataSrc$('#example').on('xhr.dt', function (e, settings, json, xhr) {for (var i = 0, ien = json.aaData.length ; i < ien ; i++) {json.aaData[i].sum = json.aaData[i].one + json.aaData[i].two;}// Note no return - manipulate the data directly in the JSON object.}).dataTable({ajax: "data.json"});7,Datatable常用Api
//全部參考 https://datatables.net/reference/api/// 1,獲取API的方式// 注意 $(selector).dataTable()得到的是table的jquery對象// 而api對象只能通過:api.$(select) 返回查找到的jquery對象。$(selector).DataTable();$(selector).dataTable().api();new $.fn.dataTable.Api(selector);// 2,得到一個api對象var table = $('#example').DataTable();//3,描畫 draw( [paging] ) 取值:true 全部重畫,false 全部重畫(保持當前的頁面),// "page" 不重取數據,只描畫當前頁$('#myFilter').on('keyup', function () {table.search(this.value).draw();});// Sort by column 1 and then re-drawtable.order([[1, 'asc']]).draw(false);table.page('next').draw('page');// data() 獲取全表數據// Increment a counter for each rowtable.data().each(function (d) {d.counter++;});// 4,column().data() 獲取列數據// cloumn的第一個參數 可以是序號,或jquery支持的選擇器// cloumn的第二個參數 是一個 selector-modifier 對象,取值如下//{// // DataTables core// order: 'current', // 'current', 'applied', 'index', 'original'// page: 'all', // 'all', 'current'// search: 'none', // 'none', 'applied', 'removed'// // Extension - KeyTable (v2.1+) - cells only// focused: undefined, // true, false, undefined// // Extension - Select (v1.0+)// selected: undefined // true, false, undefined//}table.column(3, { order: 'current' }).data();//5,row().data() 獲取行數據$('#example tbody').on('click', 'tr', function () {console.log(table.row(this).data());});// 6,row().node() 獲取行dom對象$(table.row('#row-4').node()).addClass('ready');// 7,row().remove(); 刪除當前行table.row('#row-4').remove();// 8, row.add() 加一行數據// rows.add() 加多行數據table.row.add({id:"1",name:"li"});// 9, table().body() 獲取tbody dom 對象 // table().header() 獲取theader dom 對象 // table().footer() 獲取tfooter dom 對象 // table().node() 獲取table dom 對象 $(table.table().footer()).addClass('highlight');// 10,destroy() 銷毀table true:連同html一起銷毀table.destroy(false)// 11,on 綁定table的事件table.on('xhr', function (e, settings, json) {console.log('Ajax event occurred. Returned data: ', json);});// 12,page.len(10) 設置一頁顯示的條數$('#_10').on('click', function () {table.page.len(10).draw();});??8,其他
8.1 ??重新加載數據
第二個參數為false的話,會保持當前的選中頁。
vartable = $('#example').DataTable();table.ajax.reload( function( json ) {$('#myInput').val( json.lastInput );} , true);8.2?改變url,再加載?
table.ajax.url( 'newData.json').load();8.3?獲取服務器返回的json數據
vartable = $('#example').DataTable();table.on( 'xhr', function() {varjson = table.ajax.json();alert( json.data.length +' row(s) were loaded');} );轉載于:https://www.cnblogs.com/wenhainan/p/10446512.html
總結
以上是生活随笔為你收集整理的jquery datatable的详细用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 51nod1237 最大公约数之和 V3
- 下一篇: Spring Cloud微服务系列文,服