jQuery DataTables 使用方法整理(上)

http://chengkai.wang/?post=74

*以下操作参照英文官网,在如下表格对象进行 <table id="example"><thead>...</thead><tbody></tbody></table>

1、列的可见性
$('#example').dataTable( {
  "columnDefs": [
    { "visible": false, "targets": 0 }
  ]
} );
target:列的序号,0为第一列


Hide the first column
隐藏第一列:
$('#example').dataTable( {
  "columns": [
    { "visible": false },
    null,
    null,
    null,
    null
  ] } );
} );


隐藏第三列和第四列,其中第三列不能被搜索,第四列默认支持搜索
$(document).ready(function() {
    $('#example').dataTable( {
        "columnDefs": [
            {
                "targets": [ 2 ],
                "visible": false,
                "searchable": false
            },
            {
                "targets": [ 3 ],
                "visible": false
            }
        ]
    } );
} );


排序
$('#example').dataTable( {
    "order": [[ 0, 'asc' ], [ 1, 'asc' ]]
} );

启用/禁用排序
$('#example').dataTable( {
  "ordering": false
} );


//垂直滚动,不分页
$(document).ready(function() {
    $('#example').dataTable( {
        "scrollY":        "200px",
        "scrollCollapse": true,
        "paging":         false
    } );
} );


//水平滚动
$(document).ready(function() {
    $('#example').dataTable( {
        "scrollX": true
    } );
} );


//水平滚动+垂直滚动
$(document).ready(function() {
    $('#example').dataTable( {
        "scrollY": 200,
        "scrollX": true
    } );
} );


//界面语言
$(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)"
        }
    } );
} );


{
    "emptyTable":     "No data available in table",
    "info":           "Showing _START_ to _END_ of _TOTAL_ entries",
    "infoEmpty":      "Showing 0 to 0 of 0 entries",
    "infoFiltered":   "(filtered from _MAX_ total entries)",
    "infoPostFix":    "",
    "thousands":      ",",
    "lengthMenu":     "Show _MENU_ entries",
    "loadingRecords": "Loading...",
    "processing":     "Processing...",
    "search":         "Search:",
    "zeroRecords":    "No matching records found",
    "paginate": {
        "first":      "First",
        "last":       "Last",
        "next":       "Next",
        "previous":   "Previous"
    },
    "aria": {
        "sortAscending":  ": activate to sort column ascending",
        "sortDescending": ": activate to sort column descending"
    }
}


DOM/jQuery Event 事件的绑定
把事件绑定在表格及其元素上有时候是十分有用的,但是DataTables插件的行是动态生成的,在分页状态下DOM只能获得当前分页的内容,解决这个问题的最佳办法是通过delegated事件(jQuery 0n()方法)。下面是例子:
$(document).ready(function() {
    $('#example').dataTable();
     
    $('#example tbody').on('click', 'tr', function () {
        var name = $('td', this).eq(0).text();
        alert( 'You clicked on '+name+'\'s row' );
    } );
} );



DataTables events 事件
DataTables fires a number of custom events which you can bind to in the standard jQuery fashion (although note that the namespace dt must be used), allowing your code to perform custom actions when these events occur.
DataTables 有一些可定制的第三方事件,你可以用标准的jQuery方式进行绑定(需要加上专用的命名空间.dt),然后你的代码就可以使用这些第三方事件了。
下面是一个例子,详细的更多支持事件需要去查api文档:
$(document).ready(function() {
    var eventFired = function ( type ) {
        var n = $('#demo_info')[0];
        n.innerHTML += '<div>'+type+' event - '+new Date().getTime()+'</div>';
        n.scrollTop = n.scrollHeight;      
    }
 
    $('#example')
        .on( 'order.dt',  function () { eventFired( 'Order' ); } )
        .on( 'search.dt', function () { eventFired( 'Search' ); } )
        .on( 'page.dt',   function () { eventFired( 'Page' ); } )
        .dataTable();
} );


Column rendering
Each column has an optional rendering control called columns.render DT which can be used to process the content of each cell before the data is used. columns.render DT 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.This example shows the person's age combined with their name in the first column, hiding the age column. This technique can be useful for adding links, assigning colours based on content rules and any other form of text manipulation you require:
每一列都有一个可选的内容描述方法:columns.render,它可以用于在生成数据前加载其他展示元素和规定数据的展示形式。它支持很多选项来定义数据的type(排序、搜索、显示 等),但它控制单元格内容的功能却十分易于使用,下面的例子展示了如何在第一个列里的单元格展示 年龄+姓名,然后把姓名列隐藏了。
$(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`.

                "render": function ( data, type, row ) {
                    return data +' ('+ row[3]+')';
                },
                "targets": 0
            },

            { "visible": false,  "targets": [ 3 ] }
        ]
    } );
} );


自定义分页下可选每页显示长度
两种形式:
1、一维数组  "lengthMenu": [10, 25, 50],长度参数和展示文字都是数组中的值
2、二维数组  "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]] , 第一个数组代表列表长度参数,第二个数组对应展示的文字描述,像“all”、“全部”这种。
$(document).ready(function() {
    $('#example').dataTable( {
        "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]]
    } );
} );


使用多个表格控制控件

下面代码在表格的上下各展示了一套附加控件(信息/搜索/分页/显示长度):

$(document).ready(function() {
    $('#example').dataTable( {
        "dom": '<"top"iflp<"clear">>rt<"bottom"iflp<"clear">>'
    } );
} );
*如果看不懂上面的代码啥意思,可以看看这个:http://datatables.net/reference/option/dom ,看下这些字母和符号分别代表什么dom元素。



复合表头:可将表头再分类
demo:http://datatables.net/examples/advanced_init/complex_header.html
主要代码如下:
html:--------------
 <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>
 
        <tfoot>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Salary</th>
                <th>Office</th>
                <th>Extn.</th>
                <th>E-mail</th>
            </tr>
        </tfoot>
js:------------------
$(document).ready(function() {
    $('#example').dataTable( {
        "columnDefs": [ {
            "visible": false,
            "targets": -1
        } ]
    } );
} );


把HTML内容读取到一个对象中
从dt表中读取到的每一行被装入一个javaScript对象中:
数据形式:{
    "name":    "...",
    "position":   "...",
    "office":    "...",
    "age":      "...",
    "start_date": "...",
    "salary":    "..."
}
代码如下-------------------
$(document).ready(function() {
    $('#example').DataTable({
        "columns": [
            { "data": "name" },
            { "data": "position" },
            { "data": "office" },
            { "data": "age" },
            { "data": "start_date" },
            { "data": "salary" }
        ]
    });
} );


用HTML5的data-*属性设置表格的初始化属性(详见http://datatables.net/examples/advanced_init/html5-data-options.html)
有哪些属性请看:http://datatables.net/reference/option/
jQuery会自动把带短线链接符的属性字符串转换成符合camel方式命名的属性名,eg: data-page-length 代表pageLengeth
代码示例:
js:
$(document).ready(function() {
    $('#example').DataTable();
} );
-----------------------------
html:
<table id="example" class="display" width="100%" data-page-length="25" data-order="[[ 1, &quot;asc&quot; ]]">
        ....
</table>



语言
两种方法设置语言 
1、通过option选项 ,language 
2、language.url ,把语言文件保存在外部文件,用ajax加载
下面例子是加载外部语言文件的方法:
$(document).ready(function() {
    $('#example').dataTable( {
        "language": {
            "url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/German.json"
        }
    } );
} );
上面那个German.json文件定义的表格初始化属性如下:
{
"sEmptyTable": "Keine Daten in der Tabelle vorhanden",
"sInfo": "_START_ bis _END_ von _TOTAL_ Einträgen",
"sInfoEmpty": "0 bis 0 von 0 Einträgen",
"sInfoFiltered": "(gefiltert von _MAX_ Einträgen)",
"sInfoPostFix": "",
"sInfoThousands": ".",
"sLengthMenu": "_MENU_ Einträge anzeigen",
"sLoadingRecords": "Wird geladen...",
"sProcessing": "Bitte warten...",
"sSearch": "Suchen",
"sZeroRecords": "Keine Einträge vorhanden.",
"oPaginate": {
"sFirst": "Erste",
"sPrevious": "Zurück",
"sNext": "Nächste",
"sLast": "Letzte"
},
"oAria": {
"sSortAscending": ": aktivieren, um Spalte aufsteigend zu sortieren",
"sSortDescending": ": aktivieren, um Spalte absteigend zu sortieren"
}
}


Setting defaults
.fn.dataTable.defaults
http://datatables.net/examples/advanced_init/defaults.html
自己看,我也没搞懂



Row created callback
createRow方法,在每一行生成后调用一次回调函数,
有了这个方法,我们可以额外添加一些东西,比如工资超过4000时用蓝色高亮显示,
column.createCell也可以达到类似的功能。
$(document).ready(function() {
    $('#example').dataTable( {
        "createdRow": function ( row, data, index ) {
            if ( data[5].replace(/[\$,]/g, '') * 1 > 150000 ) {
                $('td', row).eq(5).addClass('highlight');
            }
        }
    } );
} ); 


Row grouping (http://datatables.net/examples/advanced_init/row_grouping.html)
没看懂,不知道干啥用的


Footer callback
例子展示了在表格最后执行求和方法,计算某一列数值的总和:
$(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 = api
                .column( 4 )
                .data()
                .reduce( function (a, b) {
                    return intVal(a) + intVal(b);
                } );
 
            // 某一列当前显示的列的总和
            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)'
            );
        }
    } );
} );


定制的工具栏元素 Custom toolbar elements
DataTables插件在表格周围插入一些dom元素来控制DataTables的一些特性的实现,我们可以利用它的这种机制定义自己的专属dom元素,官网上的例子是用"dom"属性生成了一个自定义的class="toolbar"的div对象,
--------------------------
$(document).ready(function() {
    $('#example').dataTable( {
        "dom": '<"toolbar">frtip'
    } );
 
    $("div.toolbar").html('<b>Custom tool bar! Text/images etc.</b>');
} );
--------------------------
你可以在toolbar上面加任意你需要的元素和并绑定事件,更多复杂用法后面再研究:
For more complex features, or for creating reusable plug-ins, DataTables also has a feature plug-in API available, which can be used to create plug-ins which are used in a table by a single character reference in the domDT option (like the built in option of f refers to 'filtering input', you could have an F option which creates your own filtering input control, custom to your app).
TableTools is a feature plug-in for DataTables which adds buttons into a toolbar for a table, which controls such as copy to clipboard, export and custom buttons.


排序方式的控制-Order direction sequence control
很多时候我们想让表格的某一列或几列降序排序,而不是默认情况下的升序排列,这可以用设置初始化参数column.orderSequence的方法实现,它可以让你限制数据的排序方式,你甚至可以在排序上增加一些自定义的方法,下面的例子没有实际的应用例子,我们实际中可能不会在同一个表格中规定这么多排序规则。
eg:-----------------------------------
Column 1 - default ordering默认排序
Column 2 - default ordering 默认排序
Column 3 - ascending ordering only 仅升序
Column 4 - descending ordering, followed by ascending and then ascending again 不知道怎么翻译 @_@(外国人太坑)
Column 5 - descending ordering only 仅降序
Column 6 - default ordering 默认排序
code:------------------------
$(document).ready(function() {
    $('#example').dataTable( {
        "aoColumns": [
            null,
            null,
            { "orderSequence": [ "asc" ] },
            { "orderSequence": [ "desc", "asc", "asc" ] },
            { "orderSequence": [ "desc" ] },
            null
        ]
    } );
} );





===============Style,样式==============
基本样式:
<table id="example" class="display" cellspacing="0" width="100%">
说明:
display 涵盖下面样式
stripe  条纹状态
hover   当鼠标经过时高亮行显示
cell-border 给每个单元设置边框
row-border  给每行设置边框,注意:cell-border和row-border不能同时使用
order-column    高亮显示表格目前那列排序
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值