Examples--Advanced initialisation

1、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.

One of the best ways of dealing with this is through the use of delegated events with jQuery's on method, as shown in this example. This example also uses the DataTables row().data() method to retrieve information about the selected row - the row's data so we can show it in the alert message in this case.

$(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' );
    } );
} );

 

2、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.

All custom events fired by DataTables are fired with the namespace dt in order to prevent conflicts arising with other jQuery plug-ins which also fire events. The DataTables on() method can be used like the jQuery on() method, but will automatically append the dt namespace if required.

This example shows the use of the order, search and page events by adding a notification that the event fired to an element on the page to show that they have indeed fired.

$(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();
} );

 

3、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.

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.

$(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 ] }
        ]
    } );
} );

 

4、Page length options

It is possible to easily customise the options shown in the length menu (by default at the top left of the table) using the lengthMenu initialisation option.

This parameter can take one of two forms:

  • A 1D array of options which will be used for both the displayed option and the value, or
  • A 2D array in which the first array is used to define the value options and the second array the displayed options (useful for language strings such as 'All').

The example below shows a 2D array being used to include a "Show all" records option.

$(document).ready(function() {
    $('#example').DataTable( {
        "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]]
    } );
} );

 

5、Multiple table control elements

As is described by the basic DOM positioning example you can use the dom initialisation parameter to move DataTables features around the table to where you want them.

In addition to this, you can also use dom to create multiple instances of these table controls. Simply include the feature's identification letter where you want it to appear, as many times as you wish, and the controls will all sync up (note that obviously the table (t) should be included only once).

This is shown in the demo below where the four key built-in features are duplicated above and below the table.

$(document).ready(function() {
    $('#example').DataTable( {
        "dom": '<"top"iflp<"clear">>rt<"bottom"iflp<"clear">>'
    } );
} );

 

6、Complex headers with column visibility

Complex headers (using colspan / rowspan) can be used to group columns of similar information in DataTables, creating a very powerful visual effect.

In addition to the basic behaviour, DataTables can also take colspan and rowspan into account when working with hidden columns. The colspan and rowspan attributes for each cell are automatically calculated and rendered on the page for you. This allows the columns.visible option and column().visible() method to take into account rowspan / colspan cells, drawing the header correctly.

Note that each column must have at least one unique cell (i.e. a cell without colspan) so DataTables can use that cell to detect the column and use it to apply ordering.

The example below shows a header spanning multiple cells over the contact information, with one of the columns that the span covers being hidden.

$(document).ready(function() {
    $('#example').DataTable( {
        "columnDefs": [ {
            "visible": false,
            "targets": -1
        } ]
    } );
} );

 

7、Read HTML to data objects

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.

It can be very useful to have DataTables read the information into an object rather than an array, an option that can be triggered using the columns.data initialisation option to define how you want the data to be stored. Typically columns.data is used with Ajax sourced data to tell DataTables where to read data from, but as can be seen here it also tells DataTables where to write the data to.

This ability to store data into an object can be very useful when working with the DataTables API after the table has been initialised.

In the example shown here, the data read from each row in the table is read into a Javascript object with the structure:

$(document).ready(function() {
    $('#example').DataTable({
        "columns": [
            { "data": "name" },
            { "data": "position" },
            { "data": "office" },
            { "data": "age" },
            { "data": "start_date" },
            { "data": "salary" }
        ]
    });
} );

Please note that this feature requires DataTables 1.10.3 or newer.

 

8、HTML5 data-* attributes - table options

As of DataTables 1.10.5 it is now possible to define initialisation options using HTML5 data-* attributes. The attribute names are read by DataTables and used, potentially in combination with, the standard Javascript initialisation options (with the data-* attributes taking priority).

Please note that the attribute values must contain valid JSON data or a Javascript primitive, as required by jQuery's $().data() method. This means that double quotes should be used inside the attribute if needed for a string (see the data-order in this example).

Additionally, jQuery will convert a dashed string into the camel-case notation used by DataTables for its options. For example data-page-length is used to represent pageLength.

The table below shows the use of pageLength and order on the main table. Column options can also be defined on the table column cells, as shown by the use of the columns.orderable option on the fifth column below.

<table id="example" class="display" data-page-length="25" data-order="[[ 1, &quot;asc&quot; ]]" width="100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th data-orderable="false">Start date</th>
                <th>Salary</th>
            </tr>
        </thead>

 

9、HTML5 data-* attributes - cell data

DataTables can use different data for different actions (display, ordering and searching) which can be immensely powerful for transforming data in the display to be intuitive for the end user, while using different, or more complex data, for other actions. For example, if a table contains a formatted telephone number in the format xxx-xxxx, intuitively a user might search for the number but without a dash. Using orthogonal data for searching allows both forms of the telephone number to be used, while only the nicely formatted number is displayed in the table.

One method in which DataTables can obtain this orthogonal data for its different actions is through custom HTML5 data attributes. DataTables will automatically detect four different attributes on the HTML elements:

  • data-sort or data-order - for ordering data
  • data-filter or data-search - for search data

This example shows the use of data-sort and data-filter attributes. In this case the first column has been formatted so the first name has abbreviated, but the full name is still searchable (search for "Bruno" for example). Additionally, although the last column contains non-numeric data in it, the column will correctly order numerically as the data-sort / data-order attribute is set on the column with plain numeric data.

<table id="example" class="display" style="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>
        <tbody>
            <tr>
                <td data-search="Tiger Nixon">T. Nixon</td>
                <td>System Architect</td>
                <td>Edinburgh</td>
                <td>61</td>
                <td data-order="1303689600">Mon 25th Apr 11</td>
                <td data-order="320800">$320,800/y</td>
            </tr>
            <tr>
                <td data-search="Garrett Winters">G. Winters</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>63</td>
                <td data-order="1311552000">Mon 25th Jul 11</td>
                <td data-order="170750">$170,750/y</td>
            </tr>

 

10、Language file

As well as being able to pass language information to DataTables through the language initialisation option, you can also store the language information in a file, which DataTables can load by Ajax using the language.url option.

The following example shows DataTables reading a German language file which is hosted on the DataTables CDN

$(document).ready(function() {
    $('#example').DataTable( {
        "language": {
            "url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/German.json"
        }
    } );
} );

 

11、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. This object will take all of the same parameters as the DataTables initialisation object, but in this case you are setting the default for all future initialisations of DataTables.

This example shows the searching and ordering features of DataTables being disabled by default, which is reflected in the table when it is initialised.

$.extend( true, $.fn.dataTable.defaults, {
    "searching": false,
    "ordering": false
} );
 
 
$(document).ready(function() {
    $('#example').DataTable();
} );

 

12、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.

In this case a trivial example of making the 'salary' column blue and bold by adding a CSS class to the container cell if the salary is greater than $150,000. Note that columns.createdCell could also be used to create exactly the same effect.

$(document).ready(function() {
    $('#example').DataTable( {
        "createdRow": function ( row, data, index ) {
            if ( data[5].replace(/[\$,]/g, '') * 1 > 150000 ) {
                $('td', row).eq(5).addClass('highlight');
            }
        }
    } );
} );

 

13、Row grouping

Although DataTables doesn't have row grouping built-in (picking one of the many methods available would overly limit the DataTables core), it is most certainly possible to give the look and feel of row grouping.

In the example below the 'group' is the office location, which is based on the information in the third column (which is set to hidden). The grouping indicator is added by the drawCallback function, which will parse through the rows which are displayed, and enter a grouping TR element where a new group is found. A click event handler is added for the grouping rows to allow the grouping order to be restored as well as ordering by any other column.

RowGroup extension

Important note: DataTables now has a RowGroup extension that provides a formal API for the abilities in this demo and extends upon them in a number of significant and useful ways. This example is retained as a useful demonstration of how the drawCallback option can be used, but for new sites that make use of row grouping, it is suggested that you use the new RowGroup extension.

$(document).ready(function() {
    var groupColumn = 2;
    var table = $('#example').DataTable({
        "columnDefs": [
            { "visible": false, "targets": groupColumn }
        ],
        "order": [[ groupColumn, 'asc' ]],
        "displayLength": 25,
        "drawCallback": function ( settings ) {
            var api = this.api();
            var rows = api.rows( {page:'current'} ).nodes();
            var last=null;
 
            api.column(groupColumn, {page:'current'} ).data().each( function ( group, i ) {
                if ( last !== group ) {
                    $(rows).eq( i ).before(
                        '<tr class="group"><td colspan="5">'+group+'</td></tr>'
                    );
 
                    last = group;
                }
            } );
        }
    } );
 
    // Order by the grouping
    $('#example tbody').on( 'click', 'tr.group', function () {
        var currentOrder = table.order()[0];
        if ( currentOrder[0] === groupColumn && currentOrder[1] === 'asc' ) {
            table.order( [ groupColumn, 'desc' ] ).draw();
        }
        else {
            table.order( [ groupColumn, 'asc' ] ).draw();
        }
    } );
} );

 

14、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.

The example below shows a footer callback being used to total the data for a column (both the visible and the hidden data) using the column().data() API method and column().footer() for writing the value into the 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)'
            );
        }
    } );
} );

 

15、Custom toolbar elements

DataTables inserts DOM elements around the table to control DataTables features, and you can make use of this mechanism as well to insert your own custom elements. In this example a div with a class of '-string toolbar' is created using dom, and jQuery then used to insert HTML into that element to create the toolbar. You could put whatever HTML you want into the 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 dom 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).

There are a number of extensions for DataTables that make use of this ability. For example, Buttons is a feature plug-in for DataTables that adds buttons into a toolbar for a table (copy to clipboard, save to Excel / PDF, and more).

$(document).ready(function() {
    $('#example').DataTable( {
        "dom": '<"toolbar">frtip'
    } );
 
    $("div.toolbar").html('<b>Custom tool bar! Text/images etc.</b>');
} );
.toolbar {
    float: left;
}

The example may not work if your datatable is too long to load (huge table in html for example) since the div.toolbar node may not exist yet when $('div.toolbar').html is called.

You may have to use fnInitComplete to prevent this :

$(document).ready(function() {
    $('#example').DataTable( {
        dom: '<"toolbar">frtip'
        fnInitComplete: function(){
           $('div.toolbar').html('Custom tool bar!');
         }
    } );
} );

 

16、Order direction sequence control

At times you may wish to change the default ordering direction sequence for columns (some or all of them) to be 'descending' rather than DataTables' default ascending. This can be done through the use of the columns.orderSequence initialisation parameter. This parameter also allows you to limit the ordering to a single direction, or you could add complex behaviour to the ordering interaction.

The example below shows:

  • 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

It's worth noting that I don't have a good use case for when you might what to mix such complex ordering behaviour into a single table, but the example shows how these options can be used and therefore applied across all columns.

$(document).ready(function() {
    $('#example').DataTable( {
        "Columns": [
            null,
            null,
            { "orderSequence": [ "asc" ] },
            { "orderSequence": [ "desc", "asc", "asc" ] },
            { "orderSequence": [ "desc" ] },
            null
        ]
    } );
} );

 

posted @ 2018-06-13 19:00  铭川  阅读(232)  评论(0编辑  收藏  举报