Datatable Initialization

 

这里介绍如何使用Objects类型的数据源初始化Datatable,当然Object的来源也可以分为多种,比如JS定义的、server side定义的、从文件读取的等。对于datatable初始化来讲,基本一样。不同的地方只在于配置Data数据来源。

 

依赖包

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>

 

使用objects数据源初始化

 

(1)引进依赖包

(2)JS定义Object以及初始化Datatable

 1 <script type="text/javascript">
 2 
 3 //定义Object(也可以是经过Json格式化的Server Side Object)
 4     var objectData = [
 5 
 6     {
 7         "name" : "Tiger Nixon",
 8         "position" : "System Architect",
 9         "start_date" : "2011/04/25",
10         "office" : "Edinburgh",
11 
12     }, {
13         "name" : "Eason Wang",
14         "position" : "System Manager",
15         "start_date" : "2015/04/25",
16         "office" : "IT",
17 
18     }
19 
20     ];
21 
22     $(document).ready(function() {
23         $('#example').DataTable({  //初始化DataTable
24             data : objectData, //数据来源objectData变量
25             columns : [ {
26                 data : "name" //data 设置某一列显示哪个属性名的值,例如这一行表示,在第一列显示 属性名为name的值
27             }, {
28                 data : "position" //表示在第二列显示 属性名为position的值
29             }, {
30                 data : "start_date" //表示在第二列显示 属性名为start_date的值
31             }, {
32                 data : "office" //表示在第二列显示 属性名为office的值
33             }
34 
35             ]
36         });
37     });
38 </script>

 

(3)编写HTML,声明一个table(定义id/class),这里的列名可以随便定义,与上面的JS无关

 1 <table id="example" class="display">
 2         <thead>
 3             <tr>
 4                 <th>Name</th>
 5                 <th>Position</th>
 6                 <th>Start_date</th>
 7                 <th>Office</th>
 8             </tr>
 9         </thead>
10         <tfoot>
11             <tr>
12                 <th>Name</th>
13                 <th>Position</th>
14                 <th>Start_date</th>
15                 <th>Office</th>
16             </tr>
17         </tfoot>
18     </table>

 

(4)最终显示

 

posted on 2017-10-23 18:03  威士忌威自己  阅读(202)  评论(0)    收藏  举报