我喜欢创建(如果不存在)或更新数据表。更新有两种情况:
// get column names / keys from data array 'new_data' to 'columnNames'
// ...
if ($.fn.dataTable.isDataTable(table_id)) {
let datatable = $(table_id).DataTable();
datatable.clear();
datatable.rows.add(new_data);
datatable.draw('full-hold'); // keep current page
} else {
$(table_id).DataTable({
data: new_data,
columns: columns_array
});
}
如何区分有列更新和无列更新? 我的想法是检查 if 子句,当前表名称是否等于新数据的
columnNames
。
我尝试了datatable.columns().names()
,被认为没有功能。
if ($.fn.dataTable.isDataTable(table_id)) {
let datatable = $(table_id).DataTable();
// Get the column names of the existing DataTable
let existingColumnNames = datatable.columns().header().toArray().map(header => $(header).text());
// Check if the existing column names match the column names of the new data
let columnNamesMatch = JSON.stringify(existingColumnNames) === JSON.stringify(columnNames);
if (columnNamesMatch) {
// Only rows need to be updated
datatable.clear();
datatable.rows.add(new_data);
datatable.draw('full-hold'); // keep current page
} else {
// Both columns and rows need to be updated
datatable.clear();
datatable.destroy(); // Destroy the existing DataTable
$(table_id).DataTable({
data: new_data,
columns: columns_array
});
}
} else {
$(table_id).DataTable({
data: new_data,
columns: columns_array
});
}