DataTables表格插件使用说明

DataTables简介

  • 与EasyUI的Datagrid作用一样,比easyui更漂亮

  • Datatables是一款jquery表格插件。它是一个高度灵活的工具,可以将任何HTML表格添加高级的交互功能。

  • 支持分页、排序、搜索

  • 支持4种数据源

  • 支持多种主题

  • 拥有多种扩展

文件引入

  • 至少引入如下3个文件

<link rel="stylesheet" href="css/jquery.dataTables.min.css" />
<script type="text/javascript" src="js/jquery.js" ></script>
<script type="text/javascript" src="js/jquery.dataTables.min.js" ></script>

多种样式

  • Bootstrap 3

  • Foundation

  • Semantic UI

  • jQuery UI

  • Base

  • Bootstrap 4

导入的文件不同,具体请看官网示例:https://www.datatables.net

完整Table的HTML结构

<table id="example" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>item1</th>
            <th>item1</th>
            <th>item1</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>item1</td>
            <td>item1</td>
            <td>item1</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <th></th>
            <th></th>
            <th></th>
        </tr>
    </tfoot>
</table>
  • 想使用DataTables表格插件,至少要写<table></table>标签,然后再通过js渲染

初始化与常用配置

  • 默认初始化

$('#example').DataTable();
  • 配置初始化

$('#example').DataTable({
    "scrollY" : 350,
    "ajax" : 'http://wt.com',
    "serverSide" : true
});
  • 常用配置项

info //是否显示左下角信息
ordering  //是否开启排序
paging  //是否开启分页
searching  //是否开启查询
serverSide
ajax
data
lengthMenu: [ 10, 25, 50, 75, 100 ]  //定义每页显示记录数

DataTables支持四种数据源

  • HTML(DOM)数据源——后台模板拼接

<table id="example" class="display" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
        </tr>
    </tfoot>
    <tbody>
        <tr>
            <td>Tiger Nixon</td>
            <td>System Architect</td>
            <td>Edinburgh</td>
            <td>61</td>
            <td>2011/04/25</td>
            <td>$320,800</td>
        </tr>
        <tr>
            <td>Cedric Kelly</td>
            <td>Senior Javascript Developer</td>
            <td>Edinburgh</td>
            <td>22</td>
            <td>2012/03/29</td>
            <td>$433,060</td>
        </tr>
    </tbody>
</table>
  • Javascript数据源(Array/Objects)——优先级比HTMLDOM高

有2种类型:

二维数组:
var dataSet = [
    [ "Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800" ],
    [ "Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750" ]
];

对象数组(必须配合columns配置项):
var dataSet = [
    {
        "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"
    }
];

$(document).ready(function() {
    $('#example').DataTable( {
        data: dataSet,
        columns: [
            { title: "Name" },
            { title: "Position" },
            { title: "Office" },
            { title: "Extn." },
            { title: "Start date" },
            { title: "Salary" }
        ]
    } );
} );
  • Ajax with client-side processing数据源

服务器返回的数据格式必须是:
{
    "data": [
        [
          "Howard Hatfield",
          "Office Manager",
          "San Francisco",
          "7031",
          "2008/12/16",
          "$164,500"
        ],
        [
          "Hope Fuentes",
          "Secretary",
          "San Francisco",
          "6318",
          "2010/02/12",
          "$109,850"
        ]
    ]
}
或者
{
    "data": [
        {
            "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"
        }
    ]
}

$(document).ready(function() {
    $('#example').DataTable( {
        "ajax": '../ajax/data/arrays.txt'
    } );
} );
或
$(document).ready(function() {
    $('#example').DataTable( {
        "ajax": {
            "url": "data.json",
            "data": {
                "user_id": 451
            }
        }
    } );
} );
  • Ajax with server-side processing数据源

服务器返回的数据格式:
{
    "draw" : 1,
    "recordsTotal" : 20,
    "recordsFiltered" : 20,
    "data" : [
        [],[]
    ]
}

自定义列

  • 在DataTables表格初始化的时候进行初始化,使用columns或者columnDefs属性进行自定义列的信息

  • 能自定义列的标题显示内容样式别名数据绑定是否提供排序是否提供搜索过滤列宽默认内容等等

  • 示例

$('#example').DataTable({
    "ajax" : '{:U("getList")}',
    "serverSide" : true,
    "columns": [
        {
            "searchable": false,
            "name": "engine",
            "title" : "wutao",
            "orderable": false,
            "className": "my_class",
            "render": function ( data, type, full, meta ) {
                return '<a href="'+data+'">Download</a>';
            }
        },
        null
    ]
});

服务器模式的请求参数

  • 当使用服务器模式"serverSide" : true时,浏览器会发出一个GET请求来获取数据源

  • 请求的查询参数如下:

draw:1   //请求次数,用于响应是也要带回来
columns[0][data]:0       //第一列绑定的数据源标识,二维数组就是数字,对象数组就是key
columns[0][name]:engine      //第一列别名
columns[0][searchable]:false //不可搜索
columns[0][orderable]:true   //不可排序
columns[0][search][value]:   //搜索的条件
columns[0][search][regex]:false   //搜索是否使用正则

.....  //有多少列就有多少个columns[n]

order[0][column]:0   //指定排序的列
order[0][dir]:asc    //指定列的排序方式
start:0     //起始下标
length:10   //每页记录数
search[value]:    //全局搜索条件
search[regex]:false   //全局搜索是否使用正则
_:1492657609627      //自带标示不用理会

国际化

  • 在DataTables表格初始化时,使用language属性对表格中的文字信息进行灵活修改

  • 示例:

$('#example').dataTable( {
    "language": {
        "processing": "DataTables is currently busy",
        "emptyTable": "No data available in table",
        "info": "Showing page _PAGE_ of _PAGES_",
        "lengthMenu": "每页显示 _MENU_ 条记录",
        "search": "搜索:"
    }
} );

查询过滤(搜索)

  • 列表项目

自定义表格控制元素

  • 在DataTables表格控件初始化时,使用dom属性和initComplete回调函数来统一配置

  • 应用场景:把自定义按钮集成到DataTables上面

$('#example').dataTable( {
    "dom": "l<'#customid'>ftip",
    "initComplete": function(){
        $("#customid").append("<button></button>");
    }
} );
  • 自定义表格DOM最好把栅格加进去

$('#example').dataTable( {
    "dom": "<'.row'<'#customid.col-xs-4'><'.col-xs-8'f>><'.row'<'.col-xs-12't>>",
    "initComplete": function(){
        $("#customid").append("<button></button>");
    }
} );
  • drawCallback比initComplete优先执行

整合iCheck复选框

  • Html结构

<input type="checkbox" class="i-checks" id="checkAll">  //表头
  • JS部分

$('#example').DataTable({
    "ajax" : '{:U("getList")}',
    "serverSide" : true,
    "columns": [
        {
            "render": function ( data, type, row, meta ) {
                return '<input type="checkbox" class="i-checks item" name="ids[]" value="'+row.id+'">';
            }
        },
        null
    ],
    "drawCallback": function(){
        checkbox_init();
    }
});

//全选,全不选
function checkbox_init(){
    $(".i-checks").iCheck({checkboxClass:"icheckbox_square-green",radioClass:"iradio_square-green",})

    $('#checkAll').on('ifChecked', function(event){
        $(this).off('ifUnchecked');
        $('.item').iCheck('check');
        $(this).on('ifUnchecked', function(event){
            $('.item').iCheck('uncheck');
        })
    });

    $('.item').on('ifUnchecked',function(event){
        $('#checkAll').off('ifUnchecked');
        $('#checkAll').iCheck('uncheck');
    }).on('ifChecked',function(event){
        var state = true;
        $('.item').each(function(i){
            if(!$(this).is(':checked')){
                state = false;
            }
        });
        if(state){
            $('#checkAll').iCheck('check');
        }
    });
}
    原文作者:104828720
    原文地址: https://segmentfault.com/a/1190000009120095
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞