[JQuery] basic usage of Datatables plug-in

introduce

Datatables is a jquery table plug-in. It is a highly flexible tool that can add advanced interactive functions to any HTML table.

Basic use

Since it is a JQuery plug-in, the JQ library must be introduced before it is introduced.

JQuery library download address
https://jquery.com/download/
Baidu CDN of JQuery
https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js

Then introduce the CSS and JS files of datatables

Datatables download address
http://datatables.club/

You will get a compressed package after downloading. After decompression, you can get various CSS files and JS files of DT. You can import them as needed. Let's take the simplest and most basic as an example.
1. Create a new HTML file, introduce the basic file, and write the framework of the basic table
test.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>Datatables</title>
		<!-- introduce Datatable Style file -->
		<link rel="stylesheet" type="text/css" href="../MobileReview/plugin/DataTables-1.10.21/media/css/jquery.dataTables.css"/>
	</head>
	<body>
		<table id="example" border="1px">
			<thead>
				<th>full name</th>
				<th>Gender</th>
				<th>Age</th>
			</thead>
			<tbody>
				<tr>
					<td>Xiao Ming</td>
					<td>male</td>
					<td>19</td>
				</tr>
				<tr>
					<td>Xiao Hong</td>
					<td>female</td>
					<td>15</td>
				</tr>
			</tbody>
		</table>
		<!-- introduce Jquery file -->
		<script src="../MobileReview/plugin/jquery-3.6.0.js" type="text/javascript" charset="utf-8"></script>
		<!-- introduce Datatables file -->
		<script src="../MobileReview/plugin/DataTables-1.10.21/media/js/jquery.dataTables.js" type="text/javascript" charset="utf-8"></script>
	</body>
</html>

Don't copy my path. Now the page effect is as follows:

2. Initialization table
According to the method stated on the official website, one line of code initializes the table

We also write the above code in the script tag of test.html:

<script type="text/javascript">
	$(document).ready(function(){
		$('#example').DataTable();
	});
</script>

At this point, the table on the page looks like this

configuration option

DataTables has many options to configure. Options can be configured using the Object object passed into the constructor $(). DataTable() when creating a new Table.

language configuration options

As can be seen from the above picture, the plug-in displays tables in English by default. We can realize Chinese display by configuring the language configuration of DT (lazy writing method of datatable).
1. Create a new Zh-CN.json file in the same level directory
The contents of the file are as follows. Remember to delete the comments when using! Remember to delete the comments when using! Remember to delete the comments when using!

{
    "decimal":        "",//Decimal point represents character (in some languages, "," represents decimal point)
    "emptyTable":     "Table no data",//A string used to describe a table without data
    "info":           "Display per page _START_ to _END_ of _TOTAL_ Item data",//String used to describe the main information of the table
    "infoEmpty":      "0 to 0 of 0",//Used to describe the string displayed when there are no records in the table
    "infoFiltered":   "(filtered from _MAX_ total entries)",//This string is appended to the main information when the table is filtered
    "infoPostFix":    "",//String to continue appending after summary information
    "thousands":      ",",//Thousands separator
    "lengthMenu":     "display _MENU_ strip/page",//A string describing the page length option
    "loadingRecords": "Loading...",//Prompt string used to describe data waiting during loading - displayed when reading data asynchronously
    "processing":     "Please wait",//A string describing the loading progress
    "search":         "search:",//A string describing the search input box
    "zeroRecords":    "No related records found",//String used to describe when the table filter record is empty
    "paginate": {
        "first":      "home page",
        "last":       "Last page",
        "next":       "next page",
        "previous":   "previous page"
    },
    "aria": {
        "sortAscending":  ": Ascending arrangement",
        "sortDescending": ": Descending order"
    }
}

2. Write the following code in the object passed in DT constructor

$('#example').DataTable({
	"language":{
		"url":"./Zh-CN.json"  //Import language profile
	}
});

At this point, the page table looks like this: (forgive me for a little flaw)

In addition to the above external introduction method, you can also directly configure an Object for language, such as the following:

$('#example').DataTable({
	"language": {
		"emptyTable": "Table no data",
		"lengthMenu": "display _MENU_ strip/page",
		"loadingRecords": "Loading...",
		"processing": "Please wait",
		"search": "search:",
		"zeroRecords": "No related records found",
		"paginate": {
			"first": "home page",
			"last": "Last page",
			"next": "next page",
			"previous": "previous page"
		}
	}
});

I recommend the first one.

All parameters of language:
http://datatables.club/reference/option/

Columns column

You can use this parameter to define columns during initialization. If you use columns to define columns, you need to define multiple th (null if you don't specify any options).

This configuration is an array, and each object element in the array represents a column.
"columns": [{configuration of the first column}, {configuration of the second column},...]

For example, at the beginning, we wrote three th tags. Now we delete them and use colounms to define them:

<table id="example" border="1px">
	<thead></thead>
	<tbody></tbody>
</table>
<script type="text/javascript">
	$(document).ready(function() {
		$('#example').DataTable({
			"language": {
				"url": "./Zh-CN.json"
			},
			"columns": [{//First column
				"name": "full name", //Set a description name for the column
				"defaultContent": "Xiao Hei", //Set the default and static content of the column (it can parse HTML tags)
				"className": "", //Assign one or more class es to each cell in the column
				"contetnPadding": "", //When the table calculates the best value, padding is added to the text content
				"data": "dt_name", //Set the data source of the column, that is, how to obtain data from the data source (object / array) of the whole Table
				"orderable": false, //Turn this column on / off. Do you want to sort
				"searchable": true, //Turn on or off data filtering in this column
				"title": "full name", //Set the title of the column, equivalent to th
				"type": "string", //Set the type of the column - used when sorting or searching the column
				"visible": true, //Allows or disables the display of this column
				"width": "20%" //Column width
			}, {//Second column
				"title": "Age",
				"data": "dt_age",
				"type": "num",
				"createdCell": function(td, cellData, rowData, row, col) {
					if (cellData < 18) { //When the cell value is less than 18, the font color turns red
						$(td).css('color', 'red')
					}
				},
			},{//Third column
				"title": "Gender",
				"data": "dt_sex",
				"type": "string",
			}],
		});
	});
</script>

Most of the above attributes already know their functions by name, so I won't go into detail.

contentPadding

Usually not.

When DataTables calculates the column width to be allocated to each column, it finds the longest string in each column, constructs a temporary table, and reads the width from it. The problem with this is that "mmm" is much larger than "iiii", but the latter is a long string, so the calculation may be wrong (it is very slow to do well and put it into the dom object for measurement), so this attribute is provided as a solution. It appends its value to the text of the longest string found as a column, that is, padding.

createdCell

A callback function that reads data from an ajax or dom data source and creates cells to execute. When a cell is created, you can use the columns. Rendereoption option to supplement the dom elements that manipulate the cell, such as adding a background color.

This option corresponds to the createdRowOption callback method.
function createdCell(cell,cellData,rowData,rowIndex,colIndex)

nametypeOptional
cellnodeNotd node already created
cellDataanyNoThe data of the cell comes from the original data that has not been modified in the data source
rowDataanyNoThe data Object of the whole row may be Object or array
rowIndexintNoRow index inside DT (row number)
colIndexintNoColumn index inside DT

type

type has several values:

  1. date
  2. num
  3. num-fmt
  4. html-num
  5. html-num-fmt
  6. html
  7. string

Because the table has no data source configured, it will not be demonstrated here.

Next, go to the data source.

ajax configuration

Using this parameter allows DataTables to obtain data from a data source like jQuery ajax, and finally obtain the returned data to display the table. DataTables supports JavaScript arrays and JSON data.

The diagram here is convenient. Instead of using remote data acquisition, you can directly use the written data:
1. Create a data.json

{
	"data":[{
		"dt_name": "puppy",
		"dt_age": 18,
		"dt_sex": "male"
	},
	{
		"dt_name": "floret",
		"dt_age": 12,
		"dt_sex": "female"
	},
	{
		"dt_name": "Little fat",
		"dt_age": 23,
		"dt_sex": "male"
	}]
}

2. Configure ajax

<script type="text/javascript">
	$(document).ready(function() {
		$('#example').DataTable({
			"language": {
				"url": "./Zh-CN.json"
			},
			"columns": [{
				"name": "full name", //Set a description name for the column
				"defaultContent": "Xiao Hei", //Set the default and static content of the column (it can parse HTML tags)
				"className": "", //Assign one or more class es to each cell in the column
				"contetnPadding": "", //When the table calculates the best value, padding is added to the text content
				"data": "dt_name", //Set the data source of the column, that is, how to obtain data from the data source (object / array) of the whole Table
				"orderable": false, //Turn this column on / off. Do you want to sort
				"searchable": true, //Turn on or off data filtering in this column
				"title": "full name", //Set the title of the column, equivalent to th
				"type": "string", //Set the type of the column - used when sorting or searching the column
				"visible": true, //Allows or disables the display of this column
				"width": "20%" //Column width
			}, {
				"title": "Age",
				"data": "dt_age",
				"type": "num",
				"createdCell": function(td, cellData, rowData, row, col) {
					if (cellData < 18) { //When the cell value is less than 18, the font color turns red
						$(td).css('color', 'red')
					}
				},
			},{
				"title": "Gender",
				"data": "dt_sex",
				"type": "string",
			}],
			"ajax":{
				"url":"./data.json",//Path to request file
				// "dataSrc": "", / / the default is data
			}
		});
	});
</script>

The page table changes to:

dataSrc:
The value of this attribute is related to the returned json data. Looking at the json file above, we can find that the key name of the data we want is data, which is DT's default. We can change the key name of json by changing the value of this attribute. If it is null, there is no need for the key name.

dataSrc: '', / / if it is empty, the returned transfer data can be written as follows

[{
		"dt_name": "puppy",
		"dt_age": 18,
		"dt_sex": "male"
	},
	{
		"dt_name": "floret",
		"dt_age": 12,
		"dt_sex": "female"
	},
	{
		"dt_name": "Little fat",
		"dt_age": 23,
		"dt_sex": "male"
	}
]

These are common configurations. In addition to these, there are some common but straightforward configurations below (more configurations can be viewed directly on DT's official website):

nameexplain
deferLoadingDelay the request to load the data of the server until the table is drawn for the second time
destroyDestroy all tables that match the selection and recreate the table with new options
displayStartWhen initializing the display, start from the first data (the first page to be displayed)
domDefine the display and display order of component elements of DataTables
lengthMenuDefines the options displayed in the select that displays the number of records per page
orderCellsTopControls which cell of the header (colspan rowspan header) can be applied to the sorting response of the column
orderClassesHighlight the sorted columns in the table
orderFixedSorting always works on tables
orderMultMulti column sort control
orderSorting of tables during initialization
pageLengthChange the initialization page length (how many pieces of data per page)
pagingTypePagination button display options
rendererDisplays the component renderer type
retrieveRetrieve existing Datatables instances
rowIdData attribute, the ID set by Datatables to trTag during rendering
scrollCollapseAllow tables to decrease in height when fewer records are displayed
search.caseInsensitiveIs case sensitive when searching or filtering
search.regexAllows or disables forced encoding of regular expression characters that appear in search strings
search.searchFilter (search) criteria for the table at initialization
search.smartAllow or disable the filter only (search) function of DataTables
searchColsDefine an initial search condition for each column
searchDelaySet the interval between searches.
searchSet a global filter condition
stateDurationStatus save validity period
stripeClassesSet css class of Zebra bar (parity line)
tabIndexThe Tab key controls keyboard navigation

Tags: Javascript JQuery html

Posted on Thu, 30 Sep 2021 14:13:29 -0400 by danoli3