筆記如何在系統專案中使用 DataTables 元件
2021-06-02
系統專案的開發經常會有對表格篩選、排序、分頁的功能,藉由使用 DataTables 前端元件就能夠快速解決這個需求。
說明
安裝方式
Visual Studio 使用 libman 安裝
Bootstrap 5
"libraries": [
{
"library": "[email protected]",
"destination": "lib/datatables.net/"
},
{
"library": "[email protected]",
"destination": "lib/datatables.net-bs5/"
}
]
Bootstrap 3
{
"version": "1.0",
"defaultProvider": "cdnjs",
"libraries": [
{
"provider": "cdnjs",
"library": "[email protected]",
"destination": "lib/datatables.net/"
},
{
"provider": "cdnjs",
"library": "[email protected]",
"destination": "lib/datatables.net-bs/"
}
]
}
引用方式
Layout 的地方需要引用 css
<head>
<link href="~/lib/datatables.net-bs/dataTables.bootstrap.min.css" rel="stylesheet" />
</head>
在要使用的 View Include 相關的 js script,並且要根據 Table 的 ID 進行 init DataTables
@section scripts{
<script src="~/lib/datatables/js/jquery.dataTables.min.js"></script>
<script src="~/lib/datatables.net-bs5/dataTables.bootstrap5.min.js"></script>
<script>
$(document).ready(function () {
$('#tableId').DataTable({
"searching": true,
"pageLength": 50,
"bLengthChange": false,
"order": [[ 0, "desc" ]], // Default Order
"columnDefs": [
{ "targets": 0, "orderable": true },
{ "targets": 1, "orderable": false },
{ "targets": 1, "searchable": false },
],
"language": {
"lengthMenu": "Display _MENU_ records per page",
"zeroRecords": "沒有任何查詢結果,請調整搜尋條件後再執行。",
"info": "搜尋共有 _TOTAL_ 個項目",
"infoEmpty": "",
"infoFiltered": "(filtered from _MAX_ total records)"
}
});
});
</script>
}
此外 language 也可以用外指 JS files 的方式設定:
"language": {
"url": "@Url.Content("~/Scripts/DataTables/traditional-chinese.json")"
},
{
"processing": "處理中...",
"loadingRecords": "載入中...",
"lengthMenu": "顯示 _MENU_ 項結果",
"zeroRecords": "沒有符合的結果",
"info": "顯示第 _START_ 至 _END_ 項結果,共 _TOTAL_ 項",
"infoEmpty": "顯示第 0 至 0 項結果,共 0 項",
"infoFiltered": "(從 _MAX_ 項結果中過濾)",
"infoPostFix": "",
"search": "搜尋:",
"paginate": {
"first": "第一頁",
"previous": "上一頁",
"next": "下一頁",
"last": "最後一頁"
},
"aria": {
"sortAscending": ": 升冪排列",
"sortDescending": ": 降冪排列"
}
}
Table 的使用要注意必須包含 Thead
與 Tbody
才能正確解析。
否則會發生以下錯誤:jQuery.Deferred exception: Cannot read properties of undefined (reading 'mData') TypeError: Cannot read properties of undefined (reading 'mData')
<table class="table table-bordered table-striped" id="EmpTable">
<thead>
<tr>
<th>標頭</th>
</tr>
</thead>
<tbody>
<tr>
<td>資料</td>
</tr>
</tbody>
</table>
Custom Column Order
說明如何客製化欄位的排序方式。
// $.fn.dataTable.ext.type.order['rank-pre'] = function(d) {
DataTable.ext.type.order['rank-pre'] = function (d) {
return (d[0].toLocaleUpperCase() == 'C' ? 100 : 0) + parseInt(d.substring(1));
};
new DataTable('#example', {
columnDefs: [
{
type: 'rank',
targets: 1 // Target Column Order
}
]
});