如何使用jQuery DataTables插件从JavaScript数组中加载数据
DataTables是一个现代的jQuery插件,用于为我们的网页的HTML表格添加互动和高级控件。它是一个简单易用的插件,有大量的选项供开发者自定义修改。DataTable插件的常见功能是分页、多列排序、排序和搜索。
实现代码所需的预编译文件有
CSS :
https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css
//cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js
方法:遵循的方法是将动态数据传递给dataTable,而不是从任何文档中传递信息。采取的步骤如下。
- 传递一个JavaScript数组dataSet,作为用户的数据,其中有姓名、职务、工资和地址等数据要使用。
- 使用HTML表时,表的ID为tableID。
- Datatable被初始化为表的ID。
- 在脚本部分,JS数组是通过使用data选项传递的。
- 甚至列也是使用columns.title选项动态创建的。
例子:下面的例子演示了使用该插件从数据集的JavaScript数组中加载数据。
<!DOCTYPE html>
<html>
<head>
<meta content="initial-scale=1, maximum-scale=1,
user-scalable=0" name="viewport" />
<meta name="viewport" content="width=device-width" />
<!-- Datatable plugin CSS file -->
<link rel="stylesheet" href=
"https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css" />
<!-- jQuery library file -->
<script type="text/javascript"
src="https://code.jquery.com/jquery-3.5.1.js">
</script>
<!-- Datatable plugin JS library file -->
<script type="text/javascript" src=
"https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js">
</script>
</head>
<body>
<h2>load data from JavaScript array using Datatables</h2>
<!--HTML table with student data-->
<table id="tableID" class="display" style="width:100%">
<thead>
<tr>
<th>User name</th>
<th>Designation</th>
<th>Salary</th>
<th>Address</th>
<th>City</th>
</tr>
</thead>
</table>
<script>
var dataSet = [
[
"Tina Mukherjee",
"BPO member",
"300000",
"24,chandni chowk",
"Pune"
],
[
"Gaurav",
"Teacher",
"100750",
"esquare,JM road",
"Pune"
],
[
"Ashtwini",
"Junior engineer",
"860000",
"Santa cruz",
"mumbai"
],
[
"Celina",
"Javascript Developer",
"430060",
"crr lake side ville",
"tellapur"
],
[
"Aisha",
"Nurse",
"160000",
"rk puram",
"Delhi"
],
[
"Brad henry",
"Accountant",
"370000",
"chaurasi lane",
"Kolkatta"
],
[
"Harry",
"Salesman",
"130500",
"32, krishna nagar",
"Navi mumbai"
],
[
"Rhovina",
"Amazon supporter",
"300900",
"Aparna zone",
"hyderabad"
],
[
"Celina",
"Senior Developer",
"200000",
"23, chandni chowk",
"pune"
],
[
"Glenny",
"Administrator",
"200500",
"Nagpur",
"Maharashtra"
],
[
"Brad Pitt",
"Engineer",
"100000",
"sainikpuri",
"Delhi"
],
[
"Deepa",
"Team Leader",
"200500",
"Annanagar",
"Chennai"
],
[
"Angelina",
"CEO",
"1000000",
"JM road",
"Aundh pune"
]
];
(document).ready(function() {
('#tableID').DataTable( {
data: dataSet,
columns: [
{ title: "Name" },
{ title: "Designation" },
{ title: "Salary" },
{ title: "Address" },
{ title: "City" }
]
} );
} );
</script>
</body>
</html>
输出:
Before execute:
After execute: