並不是所有的后台開發都有美工和前端工程師來配合做頁面,為了顯示數據並有一定的美感,jQuery的DataTables插件對於像我這樣的前端菜鳥來說真是雪中送炭,當然對於專業的前端開發者來說它更是錦上添花!DataTables提供了針對表格的排序、瀏覽器分頁、服務器分頁、篩選、格式化、統計等強大功能。
工作中對程序員的學習模式才深有體會,不是從入門到精通,而是從會用到了解。對於我來說,基本都是拿到一個知識先做個東西出來,再來細細品味個中的細節,然后再慢慢理解。從粗到細,從大到小,呵呵,這種"逆向學習"的模式估計也只在互聯網常見了。
使用前要引入datatables的相關包:
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="//cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js"></script>
datatables表格展示以及數據源方式都有很多,這里用的是最常見的后端返回給前端的json格式的數據源,並且前端html里指定列的title。
后端的數據可以如下:
app.get('/test/index', function(req, res) { var data = [{name:'xiaojie',age:24,job:'developer',description:'humours'},{},{},{}]; //格式像這樣,數據省略
res.json({data:data}); });
html里僅僅聲明一個table的框架:
<table class="table b-t b-light" id="datatables"> <thead> <tr> <th>姓名</th> <th>年齡</th> <th>JOB</th> <th>描述</th>
<th>操作</th> <!--自定義列-->
</tr>
</thead>
<tbody>
</tbody>
</table>
重頭戲是js,這里有功能強大的字段,待我慢慢道來。
首先初始化一個datatables,最基本的就這樣:
$(document).ready(function() { $('#datatables').dataTable( { } ); } );
datatables太強大,記錄起來真是無處下手。 先來看個例子,然后再做詳細介紹:
<script type="text/javascript"> $(document).ready(function() { var table = $('#datatables').DataTable({ "autoWidth": false, "paging": true, //"dom": 'T<"clear"><"toolbar">Clfrtip',
"dom": 'iCflrtp', "iDisplayLength": 100, "lengthMenu": [[100, 500, 1000, -1], [100, 500, 1000, "所有"]], "tableTools": { "sSwfPath": "/js/datatables/tabletools/swf/copy_csv_xls_pdf.swf", "aButtons": [ {sExtends: "csv", oSelectorOpts: {page: "current" }}, "print"], "sRowSelect": "os", }, "stateSave": false, "processing": true, "ajax": { 'url': "/test/index", }, "order": [ [0, "asc"], [1, "asc"], [2, "desc"], ], "columnDefs": [ {width: '25%', targets: 3}, ], "columns": [{ "data": "name", }, { "data": "age", }, { "data": "job", }, { "data": "description", "visible":false }], "sPaginationType": "full_numbers", "oLanguage": { "sProcessing": "<img src='/images/datatable_loading.gif'> 努力加載數據中.", "sLengthMenu": "每頁顯示 _MENU_ 條記錄", "sZeroRecords": "抱歉, 沒有找到", "sInfo": "從 _START_ 到 _END_ /共 _TOTAL_ 條數據", "sInfoEmpty": "沒有數據", "sInfoFiltered": "(從 _MAX_ 條數據中檢索)", "sZeroRecords": "沒有檢索到數據", "sSearch": "模糊查詢: ", "oPaginate": { "sFirst": "首頁", "sPrevious": "前一頁", "sNext": "后一頁", "sLast": "尾頁" } }, });
這里面每個字段都可以說上一番,有些簡單很容易理解,像dom這種就很復雜。
展示的效果表格前面:
表格底部是分頁:
然后說明一下每個字段的效果都體現在哪里
autoWidth
用來啟用或禁用自動列的寬度計算。通常被禁用作為優化(它需要一個有限的時間量來計算的寬度),默認值是true,所以通常將它設為false
分頁paging
指定它才能顯示表格底部的分頁按鈕,如果數據量大的話,這個通常需要設置為true,當然它也與dom的值息息相關,如果dom中沒有指定p這個字符,它即使為true也是無效的。
dom
這個是我認為最復雜也是功能最強大的字段,當然目前我也只用到了它的冰山一角。
當自定義數據表時,可以根據自身喜好來設置功能元素的默認位置等,可以指定容器,由數據表給出每個HTML控制元件被表示為在domDT選項的單個字符。
dom常用的初始化字符如下:
l - Length changing 選擇每頁顯示行數下拉框的控件 f - Filtering input 搜索過濾控件 t - The Tabletools 導出excel,csv的按鈕 i - Information 顯示匯總信息(從 1 到 100 /共 1,288 條數據) p - Pagination 分頁控件 r - pRocessing 顯示加載時的進度條
C - copy 顯示復制,excel的控件 下面四種是在dom中在自定義的位置植入自定義元素和class
< and > - DIV元素
<"class" and > - DIV和Class
<"#id" and > - DIV和ID
<"#id.class" and > - DIV 和ID 和Class
這些元素的先后順序也決定了對應的控件在表格中顯示的位置。舉個例子:
"dom": 'i<"toolbar">TCflrtp', 則在匯總信息(i)左邊定義了一個div:toolbar
js如下:
$("div.toolbar").html("<button class='btn btn-primary add_server' ><span>自定義按鈕</span></button>"); $(".add_server").click(function(){ location.href ="/server/import" })
即這是在匯總信息左邊會出現一個按鈕,點擊跳轉到另一個頁面。這種方式可以在一個集成的表格里植入自定義的東西,非常贊!
對於改變頁面上元素的位置,我還願意多舉幾個例子:
example 1: 簡單的DIV和樣式元素設置
/* Results in: <div class="wrapper"> {filter} {length} {information} {pagination} {table} </div> */ $('#example').dataTable( { "dom": '<"wrapper"flipt>' } );
example 2: 每頁行數p,檢索條件f,分頁p在表格上面,表信息i在表格下面
/* Results in: <div> {length} {filter} <div> {table} </div> {information} {pagination} </div> */ $('#example').dataTable( { "dom": '<lf<t>ip>' } );
example 3: 表信息i在表上面,檢索條件f,每頁行數p,處理中r在表下面,並且有清除元素
/* Results in: <div class="top"> {information} </div> {processing} {table} <div class="bottom"> {filter} {length} {pagination} </div> <div class="clear"></div> */ $('#example').dataTable( { "dom": '<"top"i>rt<"bottom"flp><"clear">' } );
iDisplayLength和lengthMenu
這兩個元素是和dom的l字符對應的,
"iDisplayLength": 100, ------表示默認1頁是100行數據
"lengthMenu": [[100, 500, 1000, -1], [100, 500, 1000, "所有"]], -------自定義每頁顯示的行數,
iDisplayLength默認是10行,lengthMenu默認是[[10 25 50 100], [10 25 50 100]]
tableTools
這個也有很多參數,這里只寫了常見的。swf可以導出為csv,pdf,xls三種文件,若需要一種,可以在aButtons中指定
"tableTools": { "sSwfPath": "/js/datatables/tabletools/swf/copy_csv_xls_pdf.swf", "aButtons": [ {sExtends: "csv", oSelectorOpts: {page: "current" },sFileName: "test.csv", //導出為csv文件,並且指定了文件的名稱
}, "print", //打印控件
"sRowSelect": "os", },
對應的表格控件為:
stateSave
如果設置為true這個是保存當前用戶的狀態的,比如用戶選擇當前每頁顯示500行,那么他重新刷頁面這個不是默認的100行,而是記錄了用戶的行為顯示500行。
processing
這個對應dom中的r,即加載數據時顯示的進度,這個一般都設置為true,不然數據量大的話用戶可能等上幾秒卻不知怎么回事,顯示的控件如下:
ajax
即后端傳來的數據,如果按照上述傳來的數據格式的話,則下面的url就是后端指定的url:
"ajax": { 'url': "/test/index", },
order
排序,這個可以對單列排序,可以按照指定的順序,先按哪列排序再按哪列排序
"order": [ [0, "asc"], [1, "asc"], [2, "desc"], ], //表示先對第1列進行升序排序,再按照第二列升序排序,最后按照第三列降序排序
columnDefs
這個字段可以對列進行很多操作,這個字段也很復雜,功能強大
"columnDefs": [ {width: '25%', targets: 3}, ],
上面舉的例子的意思是對第四列的寬度設置占所有列寬度的25%,它還有很強大的功能,如改變某列元素的屬性,增加列等,如下:
"columnDefs": [ // 將name列變為紅色
{ "targets": [0], // 目標列位置,下標從0開始
"data": "name", // 數據列名
"render": function(data, type, full) { // 返回自定義內容
return "<span style='color:red;'>" + data + "</span>"; } }, // 增加一列,包括刪除和修改,同時將需要傳遞的數據傳遞到鏈接中
{ "targets": [4], // 目標列位置,下標從0開始
"data": "name", // 數據列名
"render": function(data, type, full) { // 返回自定義內容
return "<a href='/delete?name=" + data + "'>刪除</a> <a href='/update?name=" + data + "'>更新</a>"; } } ]
columns
這個指定了傳過來的數據的字段,visible字段默認是true,如果設置false的話,顯示的時候是隱藏的,當然也可以通過空間取消其隱藏。
sPaginationType (pagingType)
sPaginationType: 分頁樣式,支持四種內置方式,simple、simple_numbers、full和 full_numbers, 默認使用 simple_numbers。即下面四種方式:
simple: 'Previous' and 'Next' buttons only
simple_numbers: 'Previous' and 'Next' buttons, plus page numbers
full: 'First', 'Previous', 'Next' and 'Last' buttons
full_numbers: 'First', 'Previous', 'Next' and 'Last' buttons, plus page numbers
oLanguage
數據表的語言設置,默認都是英文的,可以通過修改下面源碼的字段來修改成中文,更可以改為喜歡的展現方式。
另外有點想說明下,開始對於這些個字段的命名不太理解,原來第一個小寫字母表示它接受參數的類型。
a: array s:string o:object
"oLanguage": { "sProcessing": "<img src='/images/datatable_loading.gif'> 努力加載數據中.", "sLengthMenu": "每頁顯示 _MENU_ 條記錄", "sZeroRecords": "抱歉, 沒有找到", "sInfo": "從 _START_ 到 _END_ /共 _TOTAL_ 條數據", "sInfoEmpty": "沒有數據", "sInfoFiltered": "(從 _MAX_ 條數據中檢索)", "sZeroRecords": "沒有檢索到數據", "sSearch": "模糊查詢: ", "oPaginate": { "sFirst": "首頁", "sPrevious": "前一頁", "sNext": "后一頁", "sLast": "尾頁" } },
rowCallback
還有一個常用的是rowCallback,當創建了行,但還未繪制到屏幕上的時候調用,通常用於改變行的class風格。比如為列為IP的這一行加個超鏈接,代碼接着上面的:
"rowCallback": function(row, data) { //data是后端返回的數據
if(data.ip) { $('td:eq(3)', row).html('<a target="_blank" href=http://' + data.ip + '>' + data.ip + '</a>'); } }, //$('td:eq(3)', row)表示選中第四列的元素
則這樣的話第四列的IP只要不為空值則都鏈接到自己的頁面。
datatables實在太強大,太方便,我這里說的仍然是冰山一角,下面附錄是摘自網上,常用的屬性和方法
要注意的是,要被dataTable處理的table對象,必須有thead與tbody,而且,結構要規整(數據不一定要完整),這樣才能正確處理。
以下是在進行dataTable綁定處理時候可以附加的參數:
屬性名稱 | 取值范圍 | 解釋 |
bAutoWidth | true or false, default true | 是否自動計算表格各列寬度 |
bDeferRender | true or false, default false | 用於渲染的一個參數 |
bFilter | true or false, default true | 開關,是否啟用客戶端過濾功能 |
bInfo | true or false, default true | 開關,是否顯示表格的一些信息 |
bJQueryUI | true or false, default false | 是否使用jquery ui themeroller的風格 |
bLengthChange | true or false, default true | 開關,是否顯示一個每頁長度的選擇條(需要分頁器支持) |
bPaginate | true or false, default true | 開關,是否顯示(使用)分頁器 |
bProcessing | true or false, defualt false | 開關,以指定當正在處理數據的時候,是否顯示“正在處理”這個提示信息 |
bScrollInfinite | true or false, default false | 開關,以指定是否無限滾動(與sScrollY配合使用),在大數據量的時候很有用。當這個標志為true的時候,分頁器就默認關閉 |
bSort | true or false, default true | 開關,是否讓各列具有按列排序功能 |
bSortClasses | true or false, default true | 開關,指定當當前列在排序時,是否增加classes 'sorting_1', 'sorting_2' and 'sorting_3',打開后,在處理大數據時,性能有所損失 |
bStateSave | true or false, default false | 開關,是否打開客戶端狀態記錄功能。這個數據是記錄在cookies中的,打開了這個記錄后,即使刷新一次頁面,或重新打開瀏覽器,之前的狀態都是保存下來的 |
sScrollX | 'disabled' or '100%' 類似的字符串 | 是否開啟水平滾動,以及指定滾動區域大小 |
sScrollY | 'disabled' or '200px' 類似的字符串 | 是否開啟垂直滾動,以及指定滾動區域大小 |
-- | -- | -- |
選項 | ||
aaSorting | array array[int,string], 如[], [[0,'asc'], [0,'desc']] | 指定按多列數據排序的依據 |
aaSortingFixed | 同上 | 同上。唯一不同點是不能被用戶的自定義配置沖突 |
aLengthMenu | default [10, 25, 50, 100],可以為一維數組,也可為二維數組,比如:[[10, 25, 50, -1], [10, 25, 50, "All"]] | 這個為選擇每頁的條目數,當使用一個二維數組時,二維層面只能有兩個元素,第一個為顯示每頁條目數的選項,第二個是關於這些選項的解釋 |
aoSearchCols | default null, 類似:[null, {"sSearch": "My filter"}, null,{"sSearch": "^[0-9]", "bEscapeRegex": false}] | 給每個列單獨定義其初始化搜索列表特性(這一塊還沒搞懂) |
asStripClasses | default ['odd', 'even'], 比如['strip1', 'strip2', 'strip3'] | 指定要被應用到各行的class風格,會自動循環 |
bDestroy | true or false, default false | 用於當要在同一個元素上執行新的dataTable綁定時,將之前的那個數據對象清除掉,換以新的對象設置 |
bRetrieve | true or false, default false | 用於指明當執行dataTable綁定時,是否返回DataTable對象 |
bScrollCollapse | true or false, default false | 指定適當的時候縮起滾動視圖 |
bSortCellsTop | true or false, default false | (未知的東東) |
iCookieDuration | 整數,默認7200,單位為秒 | 指定用於存儲客戶端信息到cookie中的時間長度,超過這個時間后,自動過期 |
iDeferLoading | 整數,默認為null | 延遲加載,它的參數為要加載條目的數目,通常與bServerSide,sAjaxSource等配合使用 |
iDisplayLength | 整數,默認為10 | 用於指定一屏顯示的條數,需開啟分頁器 |
iDisplayStart | 整數,默認為0 | 用於指定從哪一條數據開始顯示到表格中去 |
iScrollLoadGap | 整數,默認為100 | 用於指定當DataTable設置為滾動時,最多可以一屏顯示多少條數據 |
oSearch | 默認{ "sSearch": "", "bRegex": false, "bSmart": true } | 又是初始時指定搜索參數相關的,有點復雜,沒搞懂目前 |
sAjaxDataProp | 字符串,default 'aaData' | 指定當從服務端獲取表格數據時,數據項使用的名字 |
sAjaxSource | URL字符串,default null | 指定要從哪個URL獲取數據 |
sCookiePrefix | 字符串,default 'SpryMedia_DataTables_' | 當打開狀態存儲特性后,用於指定存儲在cookies中的字符串的前綴名字 |
sDom | default lfrtip (when bJQueryUI is false) or <"H"lfr>t<"F"ip> (when bJQueryUI is true) | 這是用於定義DataTable布局的一個強大的屬性,另開專門文檔來補充說明吧 |
sPaginationType | 'full_numbers' or 'two_button', default 'two_button' | 用於指定分頁器風格 |
sScrollXInner | string default 'disabled' | 又是水平滾動相關的,沒搞懂啥意思 |
DataTable支持如下回調函數
回調函數名稱 | 參數 | 返回值 | 默認 | 功能 |
fnCookieCallback | 1.string: Name of the cookie defined by DataTables 2.object: Data to be stored in the cookie 3.string: Cookie expires string 4.string: Path of the cookie to set | string: cookie formatted string (which should be encoded by using encodeURIComponent()) | null | 當每次cookies改變時,會觸發這個函數調用 |
fnDrawCallback | 無 | 無 | 無 | 在每次table被draw完后調用,至於做什么就看着辦吧 |
fnFooterCallback | 1.node : "TR" element for the footer 2.array array strings : Full table data (as derived from the original HTML) 3.int : Index for the current display starting point in the display array< 4.int : Index for the current display ending point in the display array 5.array int : Index array to translate the visual position to the full data array | 無 | 無 | 用於在每次重畫的時候修改表格的腳部 |
fnFormatNumber | 1.int : number to be formatted | String : formatted string for DataTables to show the number | 有默認的 | 用於在大數字上,自動加入一些逗號,分隔開 |
fnHeaderCallback | 1.node : "TR" element for the header 2.array array strings : Full table data (as derived from the original HTML) 3.int : Index for the current display starting point in the display array 4.int : Index for the current display ending point in the display array 5.array int : Index array to translate the visual position to the full data array | 無 | 無 | 用於在每次draw發生時,修改table的header |
fnInfoCallback | 1.object: DataTables settings object 2.int: Starting position in data for the draw 3.int: End position in data for the draw 4.int: Total number of rows in the table (regardless of filtering) 5.int: Total number of rows in the data set, after filtering 6.string: The string that DataTables has formatted using it's own rules | string: The string to be displayed in the information element. | 無 | 用於傳達table信息 |
fnInitComplete | 1.object:oSettings - DataTables settings object | 無 | 無 | 表格初始化完成后調用 |
fnPreDrawCallback | 1.object:oSettings - DataTables settings object | Boolean | 無 | 用於在開始繪制之前調用,返回false的話,會阻止draw事件發生;返回其它值,draw可以順利執行 |
fnRowCallback | 1.node : "TR" element for the current row 2.array strings : Raw data array for this row (as derived from the original HTML) 3.int : The display index for the current table draw 4.int : The index of the data in the full list of rows (after filtering) | node : "TR" element for the current row | 無 | 當創建了行,但還未繪制到屏幕上的時候調用,通常用於改變行的class風格 |
fnServerData | 1.string: HTTP source to obtain the data from (i.e. sAjaxSource) 2.array objects: A key/value pair object containing the data to send to the server 3.function: Function to be called on completion of the data get process that will draw the data on the page. | void | $.getJSON | 用於替換默認發到服務端的請求操作 |
fnStateLoadCallback | 1.object:oSettings - DataTables settings object 2.object:oData - Object containing information retrieved from the state saving cookie which should be restored. For the exact properties please refer to the DataTables code. | Boolean - false if the state should not be loaded, true otherwise | 無 | 在cookies中的數據被加載前執行,可以方便地修改這些數據 |
fnStateSaveCallback | 1.object:oSettings - DataTables settings object 2.String:sValue - a JSON string (without the final closing brace) which should be stored in the state saving cookie. | String - the full string that should be used to save the state | 無 | 在狀態數據被存儲到cookies前執行,可以方便地做一些預操作 |
from http://www.cnblogs.com/zhoujie