更新数据表 - 使用新的列配置

问题描述 投票:0回答:1

我喜欢创建(如果不存在)或更新数据表。更新有两种情况:

  1. 列保持不变,仅更新行
  2. 列和行要更新(不同的数据基础) 创建和更新之间的区别已经有效。

// 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()
,被认为没有功能。

javascript datatable
1个回答
0
投票
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
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.