Jquery DataTable基本使用
1,首先需要引用下面兩個(gè)文件
? ? ?<link?rel="stylesheet"?href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"?/>
>
2,DataTable支持的數(shù)據(jù)類型
https://www.datatables.net/manual/data/
2.1?數(shù)組
vardata = [["Tiger Nixon","System Architect","Edinburgh","5421","2011/04/25","$3,120"],["Garrett Winters","Director","Edinburgh","8422","2011/07/25","$5,300"] ]?2.2 對(duì)象?
[{"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?自定義實(shí)例(本質(zhì)和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的數(shù)據(jù)來源
1)DOM
如果沒有指定data,ajax選項(xiàng),則DataTable會(huì)將當(dāng)前table的html標(biāo)簽上內(nèi)容轉(zhuǎn)換成對(duì)應(yīng)的數(shù)據(jù)(Array數(shù)據(jù)形式)。
2)Html5
Data-* 標(biāo)簽上可以指定不同的值,用于排序和查找,td內(nèi)部標(biāo)簽的值對(duì)應(yīng)當(dāng)前單元格的數(shù)據(jù)。
<td data-search="21st November 2016 21/11/2016" data-order="1479686400">21st November 2016 </td>? 3)javascript
? 通過data配置,指定數(shù)據(jù)源??梢酝ㄟ^DataTables API row.add() row().remove()操作行數(shù)據(jù)。
? ? 4)Ajax?
? 通過服務(wù)器端分頁的方式,取得數(shù)據(jù)。返回的數(shù)據(jù)只能是json數(shù)組或?qū)ο?上面的2.1和2.2).?
3,有兩種分頁方式
3.1 客戶端分頁?
這種方式,代碼最簡(jiǎn)單,整個(gè)數(shù)據(jù)量在10000條以內(nèi)可以考慮。假設(shè)已經(jīng)有了下面的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>?簡(jiǎn)單調(diào)用一句話(使用默認(rèn)設(shè)置),就可以使table具有排序,查找,分頁的基本功能。
$(function () { $("#table1").DataTable({ }); });3.2 服務(wù)器端分頁
這種方式針對(duì)大數(shù)據(jù)量的table(10萬條以上),每次只讀取當(dāng)前的一頁數(shù)據(jù),分頁在后臺(tái)做。代碼相對(duì)復(fù)雜,不過頁面響應(yīng)更快,
服務(wù)器端的分頁一般要求我們先定義thead表頭,tbody可以不寫。
4,配置參數(shù)
這些配置參數(shù)可以通過javascript進(jìn)行設(shè)置,也可以直接用HTML5標(biāo)簽data-* 的方式寫在table的標(biāo)簽中。
所有的配置選項(xiàng):https://www.datatables.net/reference/option/
$(function () {$("#table1").DataTable({// 是否允許檢索"searching": false,// 是否允許排序"ordering": true,// 初期排序列//"order": [[0,'asc'],[1,'desc']],// 是否顯示情報(bào) 就是"當(dāng)前顯示1/100記錄"這個(gè)信息"info": false,// 是否允許翻頁,設(shè)成false,翻頁按鈕不顯示"paging": false,// 水平滾動(dòng)條"scrollX": false,// 垂直滾動(dòng)條"scrollY": false,// 件數(shù)選擇功能 默認(rèn)true"lengthChange": false,// 件數(shù)選擇下拉框內(nèi)容"lengthMenu": [10, 25, 50, 75, 100],// 每頁的初期件數(shù) 用戶可以操作lengthMenu上的值覆蓋"pageLength": 50,//翻頁按鈕樣式// numbers:數(shù)字// simple:前一頁,后一頁// simple_numbers:前一頁,后一頁,數(shù)字// full:第一頁,前一頁,后一頁,最后頁//full_numbers:第一頁,前一頁,后一頁,最后頁,數(shù)字//first_last_numbers:第一頁,最后頁,數(shù)字"pagingType": "full_numbers",// 行樣式應(yīng)用 指定多個(gè)的話,第一行tr的class為strip1,第二行為strip2,第三行為strip3.// 第四行以后又開始從strip1循環(huán)。。。 如果想指定成斑馬條狀,這里的class必須指定為2個(gè)。"stripeClasses": ['strip1', 'strip2', 'strip3'],// 自動(dòng)列寬"autoWidth": true,// 是否表示 "processing" 加載中的信息,這個(gè)信息可以修改"processing": true,// 每次創(chuàng)建是否銷毀以前的DataTable,默認(rèn)false"destroy": false,// 控制表格各種信息的表示位置(比較復(fù)雜) 默認(rèn):lfrtip// 具體參考:https://datatables.net/reference/option/dom"dom": 'lrtip',"language": {"processing": "DataTables is currently busy",// 當(dāng)前頁顯示多少條"lengthMenu": "Display _MENU_ records",// _START_(當(dāng)前頁的第一條的序號(hào)) ,_END_(當(dāng)前頁的最后一條的序號(hào)),_TOTAL_(篩選后的總件數(shù)),// _MAX_(總件數(shù)),_PAGE_(當(dāng)前頁號(hào)),_PAGES_(總頁數(shù))"info": "Showing page _PAGE_ of _PAGES_",// 沒有數(shù)據(jù)的顯示(可選),如果沒指定,會(huì)用zeroRecords的內(nèi)容"emptyTable": "No data available in table",// 篩選后,沒有數(shù)據(jù)的表示信息,注意emptyTable優(yōu)先級(jí)更高"zeroRecords": "No records to display",// 千分位的符號(hào),只對(duì)顯示有效,默認(rèn)就是"," 一般不要改寫//"thousands": "'",// 小數(shù)點(diǎn)位的符號(hào),對(duì)輸入解析有影響,默認(rèn)就是"." 一般不要改寫//"decimal": "-",// 翻頁按鈕文字控制"paginate": {"first": "First page","last": "Last page","next": "Next page","previous": "Previous page"},// Client-Side用,Server-Side不用這個(gè)屬性"loadingRecords": "Please wait - loading..."},// 默認(rèn)是false// 如果設(shè)為true,將只渲染當(dāng)前也的html,速度會(huì)很快,但是通過API就訪問不到所有頁的數(shù)據(jù),有利有弊//"deferRender": false,// 服務(wù)器端處理方式"serverSide": true,// ajax選項(xiàng) 可以直接簡(jiǎn)單指定成請(qǐng)求的文件//"ajax": "data.json",// 也可以用對(duì)象來配置,更加靈活"ajax": {// url可以直接指定遠(yuǎn)程的json文件,或是MVC的請(qǐng)求地址 /Controller/Actionurl: "data.json",type: 'POST',// 傳給服務(wù)器的數(shù)據(jù),可以添加我們自己的查詢參數(shù)data: function (param) {param.opportunityNO = $('#txtSearch').val();return param;},//用于處理服務(wù)器端返回的數(shù)據(jù)。 dataSrc是DataTable特有的dataSrc: function (myJson) {if (myJson.timeout) {return "";}return myJson;}},//指定用于行ID的屬性名 默認(rèn)是:DT_RowId"rowId": 'staffId',// 列定義"columns": [ {// data 可以是屬性名,或嵌套屬性(WORKTM1.ID),數(shù)組ArrOne[,] 用中括號(hào)中的字符連接數(shù)組后返回。"data": "WORKTM1",// 這里的class會(huì)應(yīng)用到td上面"className": "dt-body-right",// 列寬"width": 40,// 很靈活,描繪每個(gè)單元格// data:當(dāng)前cell的data,這個(gè)data和type有關(guān)// type:filter,display,type,sort// row:當(dāng)前行數(shù)據(jù)// 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;},// 是否可排序 默認(rèn)值:true"orderable": true,// 指定當(dāng)前列排序操作的時(shí)候,用哪一列(幾列)的數(shù)據(jù)進(jìn)行真正的排序(通常是隱藏的)"orderData": [0, 1],// 這個(gè)屬性 和type屬性相似,指定排序時(shí)候這一列該怎么轉(zhuǎn)換數(shù)據(jù),//需要用到其他的插件 詳細(xì): https://datatables.net/plug-ins/sorting/"orderDataType": "dom-text",// 是否顯示當(dāng)前列 默認(rèn)值:true"visible": false,// 是否允許搜索此列 默認(rèn)值:true"searchable": false,//這個(gè)屬性僅Client-Side有效, Server-Side在服務(wù)器端排序 //主要用于排序和篩選,指定當(dāng)前列作為什么類型進(jìn)行解析//內(nèi)置值:date,num,num-fmt,html-num,html-num-fmt,html,string// 還可以用其他插件提供的類型 :詳細(xì): https://datatables.net/plug-ins/sorting/// 有html開頭的,都會(huì)講html標(biāo)簽先移除后進(jìn)行數(shù)據(jù)處理"type": "html",// 列頭文字,如果沒有指定thead,則會(huì)生成。如何指定了thead,則會(huì)覆蓋當(dāng)前列頭文字"title": "My column title",// defaultContent:默認(rèn)值,屬性值為null或undefined就會(huì)用這個(gè)值"defaultContent": "<i>Not set</i>",// 單元格類型:"th","td""cellType" : "td",// 單元格創(chuàng)建完后的回調(diào),可以作為render的補(bǔ)充// cell:TD的dom// cellData:原始的單元格數(shù)據(jù),如何render中進(jìn)行了格式化,用$(cell).html()來取格式化后的數(shù)據(jù)// rowData:行數(shù)據(jù)// row:行號(hào)// col:列號(hào)"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屬性用于指定列范圍(可以多列)// 優(yōu)先級(jí):上面的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;},}],// 每一行創(chuàng)建完調(diào)用的函數(shù)"createdRow": function (row, data, dataIndex) {// row : tr dom// data: row data// dataIndex:row data's indexif (data[4] == "A") {$(row).addClass('important');}},// 每一行被創(chuàng)建,但還沒有被加載到document中,這個(gè)函數(shù)優(yōu)先于createdRow// 個(gè)人覺得用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被描畫后調(diào)用"headerCallback": function (thead, data, start, end, display) {//thead:dom, data:原始的datatable數(shù)據(jù),display:當(dāng)前顯示排序好的datatable數(shù)據(jù)(有可能經(jīng)過排序)// start end :當(dāng)前dispaly數(shù)據(jù)的開始結(jié)束序號(hào)$(thead).find('th').eq(0).html( 'Displaying '+(end-start)+' records' );},// tfoot被描畫后調(diào)用,通??捎糜谟?jì)算合計(jì)值"footerCallback": function (tfoot, data, start, end, display) {//tfoot:dom, data:原始的datatable數(shù)據(jù),display:當(dāng)前顯示排序好的datatable數(shù)據(jù)(有可能經(jīng)過排序)// start end :當(dāng)前dispaly數(shù)據(jù)的開始結(jié)束序號(hào)var api = this.api();$( api.column( 5 ).footer() ).html(api.column( 5 ).data().reduce( function ( a, b ) {return a + b;}, 0 ));},// 初始化,描畫都已經(jīng)完成,常用于ajax"initComplete": function( settings, json ) {$('div.loading').remove();},// 每次DataTable描畫后都要調(diào)用,調(diào)用這個(gè)函數(shù)時(shí),table可能沒有描畫完成,// 所以不要在里面操作table的dom,要操作dom應(yīng)放在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() );},// 這個(gè)函數(shù)可以改寫數(shù)字的格式化方式// 默認(rèn)DataTable用 language.thousands來解析數(shù)字,“,”"formatNumber": function ( toFormat ) {return toFormat.toString().replace(/\B(?=(\d{3})+(?!\d))/g, "'");}});});5,服務(wù)器端的參數(shù)
// 發(fā)送到服務(wù)器端的數(shù)據(jù)// draw:計(jì)數(shù)器,返回?cái)?shù)據(jù)的時(shí)候用這個(gè)值設(shè)定// start:開始記錄(0 besed index)// length:每頁條數(shù)// search[value]:檢索文字// order[i][column]:int 排序列的序號(hào) 例如:2,代表第3列排序 i代表有幾個(gè)排序,一個(gè)的話服務(wù)器端這樣寫“order[0][column]”// order[i][dir]:排序的方式"desc","asc"// 下面comuns中的i取值從0~columns.length,所有的columns信息都發(fā)送到了服務(wù)器// columns[i][data]:columns上定義的data屬性值// columns[i][name]:columns上定義的name屬性值// columns[i][searchable]:列能不能檢索// columns[i][orderable]:列能不能排序// columns[i][search][value]:列的檢索值 string// 服務(wù)器返回的數(shù)據(jù)// draw:和Request的draw設(shè)定成一樣的值// recordsTotal:所有的總件數(shù)// recordsFiltered:篩選后的總件數(shù)// data:返回的數(shù)據(jù)// 每一行數(shù)據(jù)上面,可以包含這幾個(gè)可選項(xiàng)// DT_RowId:加在行上的ID值// DT_RowClass:加在行上的Class// DT_RowData:加在行上的額外數(shù)據(jù)(object)// DT_RowAttr:加在行上的屬性(object)// error:如果有錯(cuò)誤,就設(shè)定這個(gè)值,沒有錯(cuò)誤,不要包含這個(gè)值例子:
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:初始化和數(shù)據(jù)都加載完成,和 initComplete配置等價(jià)$('#example').on('init.dt', function () {console.log('Table initialisation complete: ' + new Date().getTime());}).dataTable();// error:處理數(shù)據(jù)出錯(cuò) errMode必須為“none”,才會(huì)觸發(fā)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加載數(shù)據(jù)完成后調(diào)用,這時(shí)數(shù)據(jù)并沒有被描畫,等價(jià)于 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對(duì)象// 而api對(duì)象只能通過:api.$(select) 返回查找到的jquery對(duì)象。$(selector).DataTable();$(selector).dataTable().api();new $.fn.dataTable.Api(selector);// 2,得到一個(gè)api對(duì)象var table = $('#example').DataTable();//3,描畫 draw( [paging] ) 取值:true 全部重畫,false 全部重畫(保持當(dāng)前的頁面),// "page" 不重取數(shù)據(jù),只描畫當(dāng)前頁$('#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() 獲取全表數(shù)據(jù)// Increment a counter for each rowtable.data().each(function (d) {d.counter++;});// 4,column().data() 獲取列數(shù)據(jù)// cloumn的第一個(gè)參數(shù) 可以是序號(hào),或jquery支持的選擇器// cloumn的第二個(gè)參數(shù) 是一個(gè) selector-modifier 對(duì)象,取值如下//{// // 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() 獲取行數(shù)據(jù)$('#example tbody').on('click', 'tr', function () {console.log(table.row(this).data());});// 6,row().node() 獲取行dom對(duì)象$(table.row('#row-4').node()).addClass('ready');// 7,row().remove(); 刪除當(dāng)前行table.row('#row-4').remove();// 8, row.add() 加一行數(shù)據(jù)// rows.add() 加多行數(shù)據(jù)table.row.add({id:"1",name:"li"});// 9, table().body() 獲取tbody dom 對(duì)象 // table().header() 獲取theader dom 對(duì)象 // table().footer() 獲取tfooter dom 對(duì)象 // table().node() 獲取table dom 對(duì)象 $(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) 設(shè)置一頁顯示的條數(shù)$('#_10').on('click', function () {table.page.len(10).draw();});??8,其他
8.1 ??重新加載數(shù)據(jù)
第二個(gè)參數(shù)為false的話,會(huì)保持當(dāng)前的選中頁。
vartable = $('#example').DataTable();table.ajax.reload( function( json ) {$('#myInput').val( json.lastInput );} , true);8.2?改變url,再加載?
table.ajax.url( 'newData.json').load();8.3?獲取服務(wù)器返回的json數(shù)據(jù)
vartable = $('#example').DataTable();table.on( 'xhr', function() {varjson = table.ajax.json();alert( json.data.length +' row(s) were loaded');} );總結(jié)
以上是生活随笔為你收集整理的Jquery DataTable基本使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 花店的投资大概多少钱 给想开店的各位分享
- 下一篇: Oracle外键需要建索引吗?