datatables使用指南
2019獨角獸企業重金招聘Python工程師標準>>>
前言
之前做項目也用過datatables渲染數據表,但也是一掃而過,照著例子初始化,滿足基礎的搜索,翻頁和排序的功能就拉倒了,沒有深入閱讀了解過,這次做項目又使用到了,特此記錄,方便以后查看。
datatables 官網?(datatables 有個中文官網,怎么說呢,盡可能的看英文官方吧。)
DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, build upon the foundations of progressive enhancement, that adds all of these advanced features to any HTML table.
DataTables 是一個jquery的js庫.是一個高度靈活。它是一個高度靈活的工具,建立在漸進增強的基礎之上,它將所有這些高級特性添加到任何HTML表中。
這段我是機翻的,不通順就湊合讀吧。
1.引入文件
1.1cdn引入核心文件
?如果只使用datatables的基礎功能,那引入兩個文件就可以。
css:? //cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css
js:??//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js
?我一般都是下載下來用,剛為了寫指南,復制了一個地址加載了一下文件,發現加載速度有些慢。推薦還是下載下來用吧。
?
1.2下載到本地項目中引用
官網下載地址,點開下載地址,是一個讓你選擇下載內容的下載器(download builder?),還是全英文的,不要慫,一步一步來。
The best method for getting a hold of DataTables for use in your project depends upon your programming environment.
這句話大致意思說,使用DataTables最好的方法就是根據你自己項目實際需求去選擇。(programming environment?程序設計環境,程序設計條件)
?
The download builder below provides a simple method that you can use to build your own custom DataTables package - including only the software that you need...
這個下面的下載器,提供(provides )一個簡單的方法(method )構建你自己的習慣(custom)的DataTables 包,僅包含你想要的軟件(software )。(其實我英語不好,但是做程序久了,一些相關詞匯還是認識的吧?不行就上翻譯軟件!)
?
上面的原文,我只截取了一部分,最后一部分是說還可通過cdn,或者通過包管理器如:npm,yarn,bower下載。我就告訴你怎么選,具體你想怎么獲取看你心情
1.3下載器的使用
Step 1. Choose a styling framework(選一個樣式框架)
下載器提供了多種樣式庫讓你下載,如果項目沒有特殊UI統一要求的話,使用第一個默認樣式即可,或者根據已使用的CSS框架去選擇。
我做個項目是大數據的管理后臺,是內網使用,所以對UI上的追求不太大,我司使用的是bootstrap3,所以我下載的是bootstrap3的樣式,也就是第二個。
?
Step 2. Select packages(選擇包--主要文件)
雖然datatables是依賴jQuery的,但是不推薦在構建器中下載,使用項目中已有的jQuery即可。然后datatables的文件肯定是要選的。
關鍵是要看最后一個:
Editor-Add full editing controls to your DataTables.
編輯器-向DataTables添加完整的編輯控件。
?
如果項目需要使用Editor!
Editor is a commercial extension for DataTables, it requires a license to use it for longer than the free trial period. Please create an account or login to be able to include Editor in the package.
Editor是DataTables的商業擴展,它需要許可證才能使用超過免費試用期。請創建一個帳戶或登錄,以便能夠在包中包含編輯器。
你首先要注冊一個賬戶,然后才能選擇下載包里包含它,單個開發人員付費永久使用好像是100刀。
100多刀啊!合小700人民幣啊!我懷著敬畏的心,下載了一個試用版本,有十五天的試用期,我主要是想知道它是如何加密一個JS文件讓它可以有試用期的,而且指定試用期時間的!首先,它這個文件不能自己發生請求對吧?如果這個文件自己在運行的時候,還發送AJAX請求去校驗是否過了試用期,肯定沒人會用這個js了。因為不安全啊!
所以,當我下載了文件,打開之后我發現。文件內部定義了N多的字符串變量去混淆,有一個專用的函數去讀取混淆后的變量拼接結果去調用對應方法,還有一個內部的date方法獲取當前的時間戳和下載時間戳去做比較,如果超出指定時間,則阻斷執行,并alert出你到期提示,且提示錯誤,無發運行。
然后我又搜了一波破解教程,但是都是針對老版的,對最新版的有沒有效不知道,不過我當時信心滿滿的和老大保證,給我時間,我一點一點的逆推,肯定能破解這個!
老大點點頭,說,你先用試用版做Demo,然后轉身走了,有大概15分鐘后給我發了一個editor的文件給我,然后是一句話:我買了!浪費那時間干啥!也尊重一下知識成果。。。。
100多刀啊!合小700人民幣啊!
?
Editor依賴兩個datatables擴展
所以你要使用Editor的話,你還需要勾選上?Buttons和Select這個兩個擴展。如下圖:
?
?
Step 3. Pick a download method (選擇一個下載方法)
我是選的第二個直接下載,具體如何使用,看你喜歡啦~
?
2.學習使用
Examples index,示例索引里包含了datatables的所有動態示列,然后頁面中開頭也說了,“實踐出真知”(One of the best ways to learn how to do anything new (including software APIs!) is to get your hands dirty as quickly as possible.?)。那么開始吧,通過示列學習如何使用datatables!
2.1Basic initialisation(基礎初始化)
我最喜歡的就是datatables一點就是,文檔清晰,示列明確,告訴你要達到示中的效果,需要引入哪些JS文件和CSS文件,HTML結果是什么樣的,JS初始化代碼是什么樣子的,這樣能讓新手快速進入到狀態,快速的配置自己的demo,而且還能保證demo運行成功,能夠幫助初學者樹立自信心,堅持使用下去,學下去。
Zero configuration(零配置使用)
零配置使用地址
DataTables has most features enabled by default, so all you need to do to use it with your own tables is to call the construction function:$().DataTable();
默認情況下,DataTables啟用了大多數特性,所以您在自己的表中使用DataTables只需要調用構造函數。
?
Searching, ordering and paging goodness will be immediately added to the table, as shown in this example.
搜索、排序和分頁的好處將立即添加到表中,如本示例所示。
?
其實這個零配置使用沒啥可說的,這個就是我上面說的,它能夠讓新手快速進入到狀態,快速的配置自己的demo,而且還能保證demo運行成功,能夠幫助初學者樹立自信心,堅持使用下去,學下去。
?
Feature enable / disable(功能的啟用/禁用)
In the following example only the search feature is left enabled (which it is by default).
$(document).ready(function() {$('#example').DataTable( {"paging": false,"ordering": false,"info": false} ); } );Default ordering (sorting)(默認排序)
The order parameter is an array of arrays where the first value of the inner array is the column to order on, and the second is 'asc' (ascending ordering) or 'desc' (descending ordering) as required. order is a 2D array to allow multi-column ordering to be defined.
The table below is ordered (descending) by the Age column.
order?選項的參數是一個二維數組,允許定義多列排序,其中內部數組的第一個參數(下例的3)是要排序的列,第二個參數是排序方式(asc升序,desc降序)。
$(document).ready(function() {$('#example').DataTable( {"order": [[ 3, "desc" ]]} ); } );注意:列是從0開始計算的,例子中的“3”,實際上是第四列(Age)列。
?
Multi-column ordering(多列排序)
一句話解釋多列排序是什么意思:在當前列值相同時,引入其它列排序。
比如說:示列中Office列降序排列從Tokyo開始,有五行的數據都是Tokyo辦公室,然后按住Shift選中Salary列你看看發生了什么?
Salary列按照Office已排序的列,進行了排序。
示列:
??$(document).ready(function() {$('#example').dataTable( {columnDefs: [ {targets: [ 0 ],orderData: [ 0, 1 ]? //如果第一列進行排序,有相同數據則按照第二列順序排列}, {targets: [ 1 ],orderData: [ 1, 0 ]? //如果第二列進行排序,有相同數據則按照第一列順序排列}, {targets: [ 4 ],orderData: [ 4, 0 ]? //如果第五列進行排序,有相同數據則按照第一列順序排列} ]} ); } );orderData是指定的列數據索引。
文檔中說有兩種選項定義多列排序一個是 columns,另一個是columnDefs選項。
區別在于如果用columns選項定義列的屬性功能則必須在數組中為表中的每個列指定一個選項,如果不需要任何選項,則這些條目可以為?null?。下方的示列禁用了第一列上的過濾,而其余列沒有指定,則設置為null:
$('#example').dataTable( {"columns": [{ "orderData": [ 0, 1 ] },{ "orderData": 0, },{ "orderData": [ 2, 3, 4 ] },null,null] } );?
columnDefs與columns此非常相似,此選項允許你為表中的列分配特定選項,且包含所有columns的選項功能,只不過不需要像columns一樣為表中的每個列指選項。但是要指定targets屬性告訴DataTables應該將定義應用于哪個列:
$('#example').dataTable( {"columnDefs": [{ "orderData": [ 0, 1 ], "targets": 0 },{ "orderData": 0, "targets": 1 },{ "orderData": [ 2, 3, 4 ], "targets": 2 }] } );targets的值可以是:
- 0或正整數 - 從左數起的列索引
- 一個負整數 - 從右邊開始計數的列索引
- 字符串的類名將匹配在列的TH上
- 字符串_all- 所有列(即分配默認值)
當columns和columnDefs定義的功能選項沖突時:
?如下第一列和第二列將在表格中顯示,而所有其他列將被隱藏。
var table = $('#myTable').DataTable( {columnDefs: [{ targets: [0, 1], visible: true},{ targets: '_all', visible: false }] } );?
Hidden columns(隱藏列)
There are times when you might find it useful to display only a sub-set of the information that was available in the original table. For example you might want to reduce the amount of data shown on screen to make it clearer for the user (consider also using the?Responsive extension?for this). This is done through the?columns.visible?column option.
?有(There are)時候,僅顯示原始表(original table)有用的的信息子集(sub-set)是有用的(useful to)。例如你想減少屏幕上顯示的數據量,以便讓用戶查看起來更清晰。這里是用columns.visible列選項。
$(document).ready(function() {$('#example').DataTable( {"columnDefs": [{"targets": [ 2 ],"visible": false,"searchable": false},{"targets": [ 3 ],"visible": false}]} ); } );此外,由于隱藏數據仍然是表的一部分,因此可選地,在允許用戶訪問該數據時可以對其進行過濾或禁止過濾 ("searchable": false)。
?
HTML屬性rowspan &colspan設置表頭跨行跨列
示列地址
<table id="example" class="display" style="width:100%"><thead><tr><th rowspan="2">Name</th><th colspan="2">HR Information</th><th colspan="3">Contact</th></tr><tr><th>Position</th><th>Salary</th><th>Office</th><th>Extn.</th><th>E-mail</th></tr></thead><tbody><tr><td>Tiger Nixon</td><td>System Architect</td><td>$320,800</td><td>Edinburgh</td><td>5421</td><td>t.nixon@datatables.net</td></tr><!--........--></tbody><tfoot><tr><th>Name</th><th>Position</th><th>Salary</th><th>Office</th><th>Extn.</th><th>E-mail</th></tr></tfoot></table>?
DOM positioning(搜索,分頁,顯示條數定位)
When customising DataTables for your own usage, you might find that the default position of the feature elements (filter input etc) is not quite to your liking. To address this issue DataTables takes inspiration from the CSS 3 Advanced Layout Module and provides the dom initialisation parameter which can be set to indicate where you wish particular features to appear in the DOM. You can also specify div wrapping containers (with an id and / or class) to provide complete layout flexibility.
當定制你自己使用的數據表格時,你可能發現datatable的功能元素(feature elements)輸入,過濾等并不完全符合你項目的需求。為了解決這個問題(To address this issue)提供了Dom初始化參數(initialisation parameter)。
?
DOM定義要在頁面上顯示的表格控件元素以及按什么順序顯示.
選項
DataTables中的內置表控制元素是:
默認值是:lfrtip
/* Results in:<div class="wrapper">{length}{processing}{table}{information}{pagination}</div> */ $('#example').dataTable( {"dom": 'lrtip' } );擴展
如果使用按鈕功能使用B,使用選擇功能使用S。
?
標簽/元素
除了上面選項之外,你還可以指定div要插入到文檔中的其他元素,這些元素可用于控件元素的樣式/嵌套。要添加標簽/元素,需要以下語法:
/* Results in:<div class="wrapper">{filter}{length}{information}{pagination}{table}</div> */ $('#example').dataTable( {"dom": '<"wrapper"flipt>' } );?
多表格控件:示列地址
$(document).ready(function() {$('#example').DataTable( {"dom": '<"top"iflp<"clear">>rt<"bottom"iflp<"clear">>'} ); } );?請注意,表格“t”應該只包含一次。
State saving(狀態保存)
示例地址
DataTables has the option of being able to save the state of a table (its paging position, ordering state etc) so that is can be restored when the user reloads a page, or comes back to the page after visiting a sub-page. This state saving ability is enabled by the stateSave??option.
DataTables可以選擇保存表的狀態(其分頁位置,排序狀態等),以便在用戶重新加載頁面時可以恢復,或者在訪問子頁面后返回頁面。stateSave??選項啟用此狀態保存功能。
例子:
$(document).ready(function() {$('#example').DataTable( {stateSave: true} ); } );?
Alternative pagination(分頁類型)
示例地址
The default page control presented by DataTables (forward and backward buttons with up to 7 page numbers in-between) is fine for most situations, but there are cases where you may wish to customise the options presented to the end user. This is done through DataTables' extensible pagination mechanism, the pagingType option.
(presented by 被…承辦? up to 最多)
Datatable 提供了默認的分頁控制(前進和后退和其中最多7頁的數字按鈕),....吧啦吧啦...這是通過DataTables的可擴展分頁機制實現的,pagingType選項。
DataTables有六個內置的分頁按鈕排列:
$(document).ready(function() {$('#example').DataTable( {"pagingType": "full_numbers"} ); } );?
Scroll(表格滾動條)
垂直滾動示例?,垂直動態高度示例,水平滾動示例,水平垂直都有滾動條的示列
scrollY啟用垂直滾動。垂直滾動會將DataTable約束到給定高度,并為任何溢出當前視口的數據啟用滾動。這可以用作分頁的替代方案,以在小區域中顯示大量數據(盡管如果需要,可以同時啟用分頁和滾動)。
scrollY可取值限定高度"200px",或CSS3 "vh"單位。該vh單位實際上是瀏覽器窗口高度的百分比。因此50vh其實是窗口高度的50%。視窗大小將在調整窗口大小時動態更新。(IE9 +才支持此css3屬性)
scrollCollapse當顯示有限數量的行時,允許表格減小高度。
$(document).ready(function () {$('#example').DataTable({"scrollY": "200px", //50vh"scrollCollapse": true, //當顯示有限數量的行時,允許表格減小高度."scrollX": true, //水平滾動,配合dataTables_wrapper{width:指定像素寬;}使用"paging": true});});此示列代碼開啟“水平”,“垂直”滾動條,并且開啟了“分頁”和允許表格行數不足時“減小高度”。
?
?Comma decimal place(逗號小數位)
示列地址
A dot (.) is used to mark the decimal place in Javascript, however,?many parts of the world use a comma?(,) and other characters such as the Unicode decimal separator (?) or a dash (-) are often used to show the decimal place in a displayed number.When reading such numbers, Javascript won't automatically recognise them as numbers, however, DataTables' type detection and sorting methods can be instructed through the language.decimal option which character is used as the decimal place in your numbers. This will be used to correctly adjust DataTables' type detection and sorting algorithms to sort numbers in your table.
?點(.)用于標記Javascript中的小數位,但是,世界上許多地方都使用逗號(,),其他字符如Unicode小數點分隔符(?)或短劃線(-)通常用于顯示小數位在顯示的數字。當讀取這些數字時,Javascript不會自動將它們識別為數字,但是,可以通過language.decimal選項指示DataTables的類型檢測和排序方法,該字符用作數字中的小數位。這將用于正確調整DataTables的類型檢測和排序算法,以對表中的數字進行排序。
$(document).ready(function() {$('#example').DataTable( {"language": {"decimal": ",","thousands": "."}} ); } );language.decimal 的值為空字符串值(此處為默認值)會導致DataTables使用點(.)作為小數點。
注意:如果不指定此選項,則在排序時,像“$1.200.000,00”此類數據會被js讀作“1.2刀”,導致排序并未按照預想的值去排列,就醬,
Language options (語言選項)
示例地址
$(document).ready(function() {$('#example').DataTable( {"language": {"lengthMenu": "Display _MENU_ records per page","zeroRecords": "Nothing found - sorry","info": "Showing page _PAGE_ of _PAGES_","infoEmpty": "No records available","infoFiltered": "(filtered from _MAX_ total records)"}} ); } );注意其中的下劃線字符串,如:“lengthMenu”中的“_MENU_”字符,它將會在初始化時替換為默認顯示選擇列表,其他的依次類推,全部見?language?詳細文檔,其中還包括i18n國際化,兩種方法使用,一種是通過 language.url?ajax請求加載語言包,另一種是在初始化時直接使用language?選項將語言直接指定替換。
中文翻譯如下:
{"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": ": 以降序排列此列"} }示例:
$(document).ready(function() {$('#example').DataTable( {"language": chineseLang//chineseLang是語言包對象,如上所示} ); } );?
截止到此,datatable的簡單應用的過完了,簡單應用并未涉及到動態加載數據,服務端渲染等等,下面將在高級應用中學習到。
我是按照官網示列從頭到尾捋的,并沒做太多合并學習,所以,還是多看官網吧。
?
3.進階學習高級初始化
Examples index,示例索引里包含了datatables的所有動態示列,然后頁面中開頭也說了,“實踐出真知”(One of the best ways to learn how to do anything new (including software APIs!) is to get your hands dirty as quickly as possible.?)。那么開始吧,通過示列學習如何使用datatables!
?
DOM / jQuery events
示列地址
Events assigned to the table can be exceptionally useful for user interaction, however you must be aware that DataTables will add and remove rows from the DOM as they are needed (i.e. when paging only the visible elements are actually available in the DOM). As such, this can lead to the odd hiccup when working with events.
事件被分配給(assigned to)表格對用戶交互特別有用(exceptionally useful for user interaction),但是你必須意識到(must be aware)DataTables會根據需要從DON中添加和刪除行。因此( As such),當處理事件時(when working with events),這可能導致(lead to )奇怪的打嗝(hiccup ??)。
示列如下:
$(document).ready(function() {var table = $('#example').DataTable();$('#example tbody').on('click', 'tr', function () {var data = table.row( this ).data();alert( 'You clicked on '+data[0]+'\'s row' );} ); } );此示列給表格行綁定了點擊事件,并通過datatable返回的實例對象table,調用了datatable的api返回了當前行數據。
?
DataTables events
實例地址
DataTables會以標準jQuery方式觸發許多自定義事件(盡管請注意dt必須使用命名空間),允許代碼在發生這些事件時執行自定義操作。
我修改了一下示列,將操作觸發的事件類型輸出到了控制臺:
var table = $('#example').DataTable();$('#example').on('order.dt', function () {console.log("排序")}).on('search.dt', function () {console.log('搜索');}).on('page.dt', function () {console.log('分頁');});此時,點擊表格表頭排序,控制臺輸出了,“排序”,“搜索”。而你進行搜索和點擊分頁的時候的時候。控制臺只會輸出對應的“搜索”,“分頁”。
這是為什么呢?
order事件?說明:
order只要排序表中的數據,就會觸發該事件。這通常由最終用戶對列進行排序觸發,但也可以通過該order()方法啟動,并在完全重繪(通過調用draw())時發生。
search事件?說明:
search只要全局搜索或列搜索選項(包括來自API的調用search())(例如)觸發了表的搜索,就會觸發該事件。此外,完全重繪(通過調用draw())方法將導致重新搜索表。
都提到了draw()方法,那看看draw方法說明:
當您執行添加或刪除行的操作時,更改表的排序,過濾或分頁特征,您將希望DataTables更新顯示以反映這些更改。此功能是為此目的而提供的......
order 事件觸發的完全重繪導致重新搜索表,則觸發了search事件。如果還沒理解,將代碼改為如下,打開控制臺再感受一下。
var table = $('#example').DataTable();$('#example').on('order.dt', function () {console.log("排序")}).on('search.dt', function () {console.log('搜索');}).on('page.dt', function () {console.log('分頁');});table.order([ [5, 'desc'] ]).draw( false );?
Column rendering (列渲染)
示列地址
Each column has an optional rendering control called columns.render which can be used to process the content of each cell before the data is used. columns.render has a wide array of options available to it for rendering different types of data orthogonally (ordering, searching, display etc), but it can be used very simply to manipulate the content of a cell, as shown here.
每列都有一個可選的(optional? 記憶技巧:option 選擇 + al …的 → 可選擇的)渲染控制器叫?columns.render 可以(can be used)在數據使用之前使用它來處理每個單元格的內容.....
下方示列顯示人員的年齡與第一列中的姓名相結合,隱藏年齡列。此技術可用于添加鏈接,根據內容規則分配顏色以及您需要的任何其他形式的文本操作。
$(document).ready(function() {$('#example').DataTable( {"columnDefs": [{// The `data` parameter refers to the data for the cell (defined by the// `data` option, which defaults to the column being worked with, in// this case `data: 0`.// “data”參數指的是(當前)單元格的數據(由“data”選項定義,默認為正在使用的列,在本例中//為“data:0”)。"render": function ( data, type, row ) {console.log(data);console.log(type);console.log(row);return data +' ('+ row[3]+')';//如果行數據為Object 此處取值為對應key,如: //return data +' ('+ row["key"]+')'},"targets": 0},{ "visible": false, "targets": [ 3 ] }//隱藏了第三列]} ); } );更詳細的用法可在?columns.render ?中看到,包括如下等等
從對象數組創建逗號分隔列表:
$('#example').dataTable( {"ajaxSource": "sources/deep.txt","columns": [{ "data": "engine" },{ "data": "browser" },{"data": "platform","render": "[, ].name"}] } );作為對象,為不同類型提取不同的數據:
// This would be used with a data source such as: // { "phone": 5552368, "phone_filter": "5552368 555-2368", "phone_display": "555-2368", ... } // Here the `phone` integer is used for sorting and type detection, while `phone_filter` // (which has both forms) is used for filtering for if a user inputs either format, while // the formatted phone number is the one that is shown in the table. $('#example').dataTable( {"columnDefs": [ {"targets": 0,"data": null, // Use the full data source object for the renderer's source"render": {"_": "phone","filter": "phone_filter","display": "phone_display"}} ] } );上例子中,filter 使用的過濾搜索數據phone_filter數據,display顯示則使用phone_display數據。
?
Page length options (表格顯示條目數選項)
示列地址
$(document).ready(function() {$('#example').DataTable( {//二維數組,它將第一個內部數組用作頁面長度值,第二個內部數組用作顯示的選項。"lengthMenu": [[10, 25, 50, -1], ['10條', '25個', '50條數據', "All"]]} );} );?
Read HTML to data objects (將HTML讀取到數據對象)
示列地址
When DataTables reads the table content from an HTML table (rather than an Ajax or Javascript data source), by default it will read the information in the table into an array that DataTables stores internally. Each array element represents a column.
當datatables從html表讀取表內容(rather than而不是Ajax 或 JS數據源),默認情況下,它將把表中的信息讀入DataTables內部存儲的數組中。每個數組元素表示一個列。
HTML5 data-* attributes
table options?表格選項??
jQuery會將虛線字符串轉換為DataTables用于其選項的駝峰式表示法。例如data-page-length 用于表示pageLength。
cell data 單元格數據?
?
Setting defaults (設置默認值)
示列地址
When working with DataTables over multiple pages it is often useful to set the initialisation defaults to common values (for example you might want to set dom to a common value so all tables get the same layout). This can be done using the $.fn.dataTable.defaults object.?
在多個頁面上使用DataTables時,將初始化默認值設置為常用值通常很有用(例如,您可能希望設置 dom為公共值,以便所有表格都具有相同的布局)。這可以使用$.fn.dataTable.defaults對象完成。
$.extend( true, $.fn.dataTable.defaults, {"searching": false,"ordering": false } );$(document).ready(function() {$('#example').DataTable(); } );$.extend:
jQuery.extend() 函數用于將一個或多個對象的內容合并到目標對象。如果多個對象具有相同的屬性,則后者會覆蓋前者的屬性值。
$.extend( target [, object1 ] [, objectN ] )指示是否深度合并
$.extend( [deep ], target, object1 [, objectN ] )警告:?不支持第一個參數傳遞 false 。
| deep | 可選。 Boolean類型 指示是否深度合并對象,默認為false。如果該值為true,且多個對象的某個同名屬性也都是對象,則該"屬性對象"的屬性也將進行合并。 |
| target | Object類型 目標對象,其他對象的成員屬性將被附加到該對象上。 |
| object1 | 可選。 Object類型 第一個被合并的對象。 |
| objectN | 可選。 Object類型 第N個被合并的對象。 |
?
Row created callback(行創建回調)
示列地址
The following example shows how a callback function can be used to format a particular row at draw time. For each row that is generated for display, the createdRow function is called once and once only. It is passed the create row node which can then be modified.
以下示例顯示了如何使用回調函數在繪制時格式化特定行。對于為顯示而生成的每一行,該 createdRow函數只調用一次和一次。它傳遞給創建行節點,然后可以對其進行修改。
$(document).ready(function() {$('#example').DataTable( {"createdRow": function ( row, data, index ,cell) {//row:剛剛創建的行元素,如:<tr role="row" class="odd">...</tr>//data:此行的原始數據源(數組或對象)//index:DataTables內部存儲中行的索引。//cell:從1.10.17開始:列的單元格。[td,td,td,td,td]if ( data[5].replace(/[\$,]/g, '') * 1 > 150000 ) {$('td', row).eq(5).addClass('highlight');}}} ); } );createdRow
在TR創建元素(并且TD已插入所有子元素)時執行此回調,或者在使用DOM源時注冊,允許操作TR元素。這在使用延遲呈現(deferRender)或服務器端處理(serverSide)時特別有用,因此您可以在創建行時添加事件,類名信息或以其他方式格式化行。
deferRender描述:
默認情況下,當從一個Ajax或Javascript數據源的數據表的負載數據(ajax和data分別地),將創建所需的前期所有HTML元素。使用大型數據集時,此操作可能需要花費不少的時間,尤其是在IE6-8等舊版瀏覽器中。此選項允許DataTables僅在繪圖需要時才創建節點(表體中的行和單元格)。
作為一個例子來幫助說明這一點,如果你加載一個10,000行的數據集,但是一個只有10條記錄的分頁顯示長度,而不是創建所有10,000行,當啟用延遲渲染時,DataTables將只創建10個。用戶對數據進行排序,分頁或過濾,將自動創建下一個顯示所需的行。這有效地分散了在頁面的整個生命周期中創建行的負載。
$('#example').dataTable( {"ajax": "sources/arrays.txt","deferRender": true } );與columns.render的區別:
也可以閱讀渲染器文檔加深理解。
?
header/footer callback
示列地址
Through the use of the header and footer callback manipulation functions provided by DataTables (headerCallback and footerCallback), it is possible to perform some powerful and useful data manipulation functions, such as summarising data in the table.
通過使用datatable提供的的header和footer回調函數,可以進行一些強有力的數據操作函數,例如統計表中的數據。
$(document).ready(function() {$('#example').DataTable( {"footerCallback": function ( row, data, start, end, display ) {var api = this.api(), data;// Remove the formatting to get integer data for summationvar intVal = function ( i ) {return typeof i === 'string' ?i.replace(/[\$,]/g, '')*1 :typeof i === 'number' ?i : 0;};// Total over all pagestotal = api.column( 4 ).data().reduce( function (a, b) {return intVal(a) + intVal(b);}, 0 );// Total over this pagepageTotal = api.column( 4, { page: 'current'} ).data().reduce( function (a, b) {return intVal(a) + intVal(b);}, 0 );// Update footer$( api.column( 4 ).footer() ).html('$'+pageTotal +' ( $'+ total +' total)');}} ); } );?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
轉載于:https://my.oschina.net/swmhxhs/blog/2991067
總結
以上是生活随笔為你收集整理的datatables使用指南的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java程序打包成exe安装包总结
- 下一篇: Android 引用第三方开源库,出现冲