datatables使用指南

前言

之前做项目也用过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- 所有列(即分配默认值)

columnscolumnDefs定义的功能选项冲突时:

  1. columns定义的属性将始终优先于columnDefs定义的属性的任何值。
  2. 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 单元格数据 

  1. data-sort或data-order- 用于排序数据
  2. data-filter或data-search- 用于搜索数据
     

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,且多个对象的某个同名属性也都是对象,则该"属性对象"的属性也将进行合并。
targetObject类型 目标对象,其他对象的成员属性将被附加到该对象上。
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的区别:

  1. 调用顺序上,columns.render 是在createdRow 之前调用的。
  2. columns.render这个属性可以操作从数据源读取到的数据。 columns.data和 columns.render比较像,说前者是只读,后者稍微复杂点可以/
  3. columns.render 可以看做为把请求过来的数据做进一步的处理, 比较常见的操作有格式化字符串替换字符串截取等等其他处理数据的方式。
  4. columns.render 主要针对的是单元格数据的处理。
  5. 没有官方给的操作TR元素

也可以阅读渲染器文档加深理解。

 

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 summation
            var intVal = function ( i ) {
                return typeof i === 'string' ?
                    i.replace(/[\$,]/g, '')*1 :
                    typeof i === 'number' ?
                        i : 0;
            };
 
            // Total over all pages
            total = api
                .column( 4 )
                .data()
                .reduce( function (a, b) {
                    return intVal(a) + intVal(b);
                }, 0 );
 
            // Total over this page
            pageTotal = 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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值