{hero}

DataTable.use()

自:DataTables 2.1 起

取得 / 設定 DataTables 使用的函式庫或全域物件。

描述

當在不使用全域 window 作為基礎的環境中載入 DataTables 時 (例如 ES Modules),您可能需要告知它可以使用的外部函式庫。例如,DataTables 可以使用 Moment.js 或 Luxon 來處理格式化的日期和時間。在瀏覽器中,這些函式庫會自動附加到全域 window,但在模組載入器中則不可能。對於這種情況,請使用此方法使其可供 DataTables 使用。

也可以傳入 window 物件,這對於在無頭環境中建構 DataTable 很有用。

重要:如果您將 Moment.js 或 Luxon 設定為用於日期/時間操作的函式庫,DataTables 只希望使用這兩個函式庫中的一個。請勿同時設定兩者。

請注意,此方法主要在您使用 ES 模組或 Common JS 載入時有用。如果您使用 script 標籤載入 DataTables 和任何相依性,它們將會自動偵測,您通常不需要使用此方法。

類型

function use(type)

描述

取得已設定要使用的函式庫。

參數
返回

任意

將會返回 DataTables 目前正在使用的請求函式庫。

function use(library)

描述

設定函式庫或 DataTables 用於操作的全域物件 (即 window),例如使用自動偵測函式庫的日期和時間操作。

參數
返回

不傳回任何值。

function use(type, library)

描述

設定函式庫或 DataTables 用於操作的全域物件 (即 window),例如指定函式庫的日期和時間操作。

參數
返回

不傳回任何值。

範例

使用 Moment.js 偵測格式化的日期

import moment from 'moment';
import DataTable from 'datatables.net';

// Tell DataTables that it can use Moment for date formatting
DataTable.use(moment, 'moment');

// Tell DataTables what date format you want to look for in the HTML data
DataTable.datetime('D MMM YYYY');

// Initialise DataTables
new DataTable('#example');

使用 Luxon 將資料呈現為特定格式

import luxon from 'luxon';
import DataTable from 'datatables.net';

// Tell DataTables that it can use Luxon for date formatting
DataTable.use(luxon, 'luxon');

// Initialise DataTables with a specific column formatting date information
new DataTable('#example', {
    columnDefs: [
        {
            targets: 4,
            render: DataTable.render.datetime('d MMM yyyy')
        }
    ]
});