强大 JavaScript&jQuery数据表插件 Datatable.js

  • 源码大小:50.18KB
  • 所需积分:1积分
  • 源码编号:19JP-3484
  • 浏览次数:772次
  • 最后更新:2023年06月18日
  • 所属栏目:表格
本站默认解压密码:19jp.com 或 19jp_com

简介

对于一个希望以易读、用户友好和快速的方式显示任何类型信息的网站来说,数据表是最重要和有用的元素之一

借助datatable.js JavaScript库,您可以轻松生成一个功能丰富的数据表,支持任何数据类型,如静态HTML表、js数组、js对象和Ajax JSON数据。它也是一个强大的JavaScript数据表插件,省去了构建自己的分页、过滤和排序引擎的所有麻烦。兼容jQuery和Vanilla JavaScript。

如何使用它:

1.在文档中下载并加载Datatable.js插件的文件。

<!-- Vanilla JS -->
<link rel="stylesheet" href="css/datatable.min.css" />
<script src="js/datatable.min.js"></script>

<!-- jQuery -->
<link rel="stylesheet" href="css/datatable.min.css" />
<script src="js/datatable.min.js"></script>
<script src="/path/to/cdn/jquery.min.js"></script>
<script src="js/datatable.jquery.min.js"></script>

2.在HTML表旁边创建一个空的分页容器。

<table class="table">
  <thead>
    ... table header ...
  </thead>
  <tbody>
    ... table body ...
  </tbody>
</table>
<!-- Pagination Links Will Be Placed Here -->
<div id="myPagi"></div>

3.调用HTML表上的函数,插件会处理剩下的部分。

// Vanilla JavaScript
var myTable = new DataTable(document.querySelector('.table'), {

    // number of entries per page
    pageSize: 10,

    // enable SORT on specific columns
    sort: [true, true, false],

    // enable FILTER on specific columns
    filters: [true, false, 'select'],
    
    // selector of pagination control
    pagingDivSelector: "#myPagi",

});

// jQuery
$('.table').datatable({

  // number of entries per page
  pageSize: 10,

  // enable SORT on specific columns
  sort: [true, true, false],

  // enable FILTER on specific columns
  filters: [true, false, 'select'],
  
  // selector of pagination control
  pagingDivSelector: "#myPagi",
    
});

4.该插件不仅适用于堆叠的HTML表,还适用于以下任何数据类型:

var myTable = new DataTable(document.querySelector('.table'), {
    data: [
      ['jQuery', 'Script'],
      ['Google', 'Com'],
      ['Facebook', 'Com']
    ]
});

// OR
var myTable = new DataTable(document.querySelector('.table'), {
    data: [
      {firstname: 'jQuery', lastname: 'Script'},
      {firstname: 'Google',  lastname: 'Com'},
      {firstname: 'Facebook', lastname: 'Com'}
    ]
});

// OR AJAX (JSON) Data
var myTable = new DataTable(document.querySelector('.table'), {
    data: {
      // path to the service
      url: "/path/to/get",

      // post or get
      type: "post", 

      // total amount of data to load, 
      size: null,  

      // determine whether to load all data in one AJAX call
      allInOne: false, 

      // set to a positive value to refresh the data every X milliseconds
      refresh: false,
    }
});

5.用于自定义数据表的所有默认选项和回调函数。

var myTable = new DataTable(document.querySelector('.table'), {
    /**
     * Specify whether the type of the column should be deduced or not. If this option
     * is true, the type is not deduced (mainly here for backward compatibility).
     *
     * @see dataTypes
     */
    forceStrings: false,

    /**
     * Specify the class of the table.
     *
     */
    tableClass: 'datatable',

    /**
     * Specify the selector for the paging div element.
     *
     */
    pagingDivSelector: '.paging',

    /**
     * Specify the class for the paging div element.
     *
     */
    pagingDivClass: 'text-center',

    /**
     * Specify the class for the paging list element.
     *
     */
    pagingListClass: 'pagination',

    /**
     * Specify the class for the paging list item elements.
     *
     */
    pagingItemClass: '',

    /**
     * Specify the class for the paging list link elements.
     *
     */
    pagingLinkClass: '',

    /**
     * Specify the href attribute for the paging list link elements.
     *
     */
    pagingLinkHref: '',

    /**
     * Specify the tabindex attribute for the paging list link elements when
     * disabled.
     *
     */
    pagingLinkDisabledTabIndex: false,

    /**
     * Specify the selector for the counter div element.
     *
     * @see counterText
     */
    counterDivSelector: '.counter',

    /**
     * Specify the selector the loading div element.
     *
     * @see data
     */
    loadingDivSelector: '.loading',

    /**
     * Sepcify the sort options.
     *
     * @type boolean|string|Array|Object
     */
    sort: false,

    /**
     * Specify the default sort key.
     *
     * @type boolean|int|string.
     */
    sortKey: false,

    /**
     * Specify the default sort directions, 'asc' or 'desc'.
     *
     */
    sortDir: 'asc',

    /**
     * Specify the number of columns, a value of -1 (default) specify
     * the the number of columns should be retrieved for the <thead>
     * elements of the table.
     *
     */
    nbColumns: -1,

    /**
     * Specify the number of elements to display per page.
     *
     */
    pageSize: 20,

    /**
     * Specify the number of pages to display in the paging list element.
     *
     */
    pagingNumberOfPages: 9,

    /**
     * Specify the way of identifying items from the data array:
     *
     *   - if this option is false (default), no identification is provided.
     *   - if a Function is specified, the function is used to identify:
     *         function (id, item) -> boolean
     *   - if an int or a string is specified, items are identified by the
     *     value corresponding to the key.
     *
     * @type boolean|int|string|Function.
     *
     */
    identify: false,

    /**
     * Callback function when the table is updated.
     *
     */
    onChange: function (oldPage, newPage) { },

    /**
     * Function used to generate content for the counter div element.
     *
     */
    counterText: function (currentPage, totalPage,
                           firstRow, lastRow,
                           totalRow, totalRowUnfiltered) {
        var counterText = 'Page ' + currentPage + ' on ' + totalPage
            + '. Showing ' + firstRow + ' to ' + lastRow + ' of ' + totalRow + ' entries';
        if (totalRow != totalRowUnfiltered) {
            counterText += ' (filtered from ' + totalRowUnfiltered + ' total entries)';
        }
        counterText += '.';
        return counterText;
    },

    /**
     * Content of the paging item pointing to the first page.
     *
     */
    firstPage: '&lt;&lt;',

    /**
     * Content of the paging item pointing to the previous page.
     *
     */
    prevPage: '&lt;',

    /**
     *
     */
    pagingPages: false,

    /**
     * Content of the paging item pointing to the next page.
     *
     */
    nextPage: '&gt;',

    /**
     * Content of the paging item pointing to the last page.
     *
     */
    lastPage: '&gt;&gt;',

    /**
     * Specify the type of the columns:
     *
     *   - if false, the type is not deduced and values are treated as strings.
     *   - if true, the type is deduced automatically.
     *   - if an Array is specified, the type of each column is retrieve from the
     *     array values, possible values are 'int', 'float' <> 'double', 'date' <> 'datetime',
     *     false <> true <> 'string' <> 'str'. A function can also be specified to convert
     *     the value.
     *
     * @see forceStrings
     *
     */
    dataTypes: true,

    /**
     * Specify the filter options.
     *
     */
    filters: {},

    /**
     * Specify the placeholder for the textual input filters.
     */
    filterText: 'Search... ',

    /**
     * Specify the placeholder for the select input filters.
     */
    filterEmptySelect: '',

    /**
     *
     */
    filterSelectOptions: false,

    /**
     *
     */
    filterInputClass: 'form-control',

    /**
     *
     */
    filterSelectClass: 'form-control',

    /**
     * Callback function before the display is reloaded.
     *
     */
    beforeRefresh: function () { },

    /**
     * Callback function after the display has been reloaded.
     *
     */
    afterRefresh: function () { },

    /**
     * Function used to generate the row of the table.
     *
     */
    lineFormat: function (id, data) {
        var res = document.createElement('tr');
        res.dataset.id = id;
        for (var key in data) {
            if (data.hasOwnProperty(key)) {
                res.innerHTML += '<td>' + data[key] + '</td>';
            }
        }
        return res;
    }
});

// OR
var myTable = new DataTable(document.querySelector('.table'), {
    data: [
      {firstname: 'jQuery', lastname: 'Script'},
      {firstname: 'Google',  lastname: 'Com'},
      {firstname: 'Facebook', lastname: 'Com'}
    ]
});

// OR AJAX (JSON) Data
var myTable = new DataTable(document.querySelector('.table'), {
    data: {
      // path to the service
      url: "/path/to/get",

      // post or get
      type: "post", 

      // total amount of data to load, 
      size: null,  

      // determine whether to load all data in one AJAX call
      allInOne: false, 

      // set to a positive value to refresh the data every X milliseconds
      refresh: false,
    }
});

// jQuery
$('.table').datatable({

  // number of entries per page
  pageSize: 10,

  // enable SORT on specific columns
  sort: [true, true, false],

  // enable FILTER on specific columns
  filters: [true, false, 'select'],
  
  // selector of pagination control
  pagingDivSelector: "#myPagi",

});

6.API方法。

// refresh the data table
myTable.refresh();

// destroy the plugin
myTable.destroy();

// set an option
myTable.option(OptionName, Value);

// load the specified page
myTable.page(number);

// get the current page number
myTable.page();

// reset all filters
myTable.reset-filters();

// retrieve all the element
myTable.select();

// retrieve the first element found with the specified ID
myTable.select(ID);

// retrieve a filtered set of elements
myTable.select(FUNCTION);

// add more data to the data array
myTable.insert(Element/[E1, E2, ...]);

// update the first element found with the specified ID with the new specified data
myTable.update(ID, Element);

// delete the first element found with the specified ID otherwise
myTable.delete(ID);

// delete all the element matching the specified function if a function is specified
myTable.delete(FUNCTION);

预览截图