如何动态更新DataTables列(和其他属性)?

时间:2014-09-21 20:50:32

标签: javascript jquery datatables

关于动态更新DataTables中的列,有几个问题,但它们似乎都过时,因为它们引用了aoColumns等弃用的属性。

我的代码看起来像这样:

var oTableOptions = {
    columns: [
        {title: "Column 1", data: "col1"},
        {title: "Column 2", data: "col2"},
        {title: "Column 3", data: "col3"}
    ],
    order: [
        [0, 'desc'],
        [1, 'asc']
    ],
    paging: false,
    searching: false,
    info: false
}

var dt = $('#tableId').DataTable(oTableOptions);

几个问题:

  1. 如何更新默认排序顺序?如果我想将其动态更改为类似[[0, 'asc'], [1, 'asc']]的内容(下次重绘表格时),我该怎么做?
  2. 以下代码有效,所以我缺少什么?

    dt.order = [[0, 'asc'], [1, 'asc']];
    dt.ajax.reload();
    
    1. 如何重命名现有列?我找不到任何记录的方法来执行此操作。有没有,或者我只是必须直接使用jQuery?

    2. 如何添加/删除列?

1 个答案:

答案 0 :(得分:2)



var oTableOptions = {
    columns: [
        {title: "Column 1", data: "col1"},
        {title: "Column 2", data: "col2"},
        {title: "Column 3", data: "col3"},
        {title: "Column 4", data: "col4"}
    ],
    order: [
        [0, 'desc'],
        [1, 'asc']
    ],
    paging: false,
    searching: false,
    info: false
}

var dt = $('#tableId').DataTable(oTableOptions);

// Later...

var nTableOptions = {
    columns: [
        {title: "Column 1", data: "col1"},
        {title: "Column 2 n", data: "col2"}, // Rename
        {title: "Column 3", data: "col3"},
        {title: "Column 4", data: "col4"} // New
    ],
    order: [
        [0, 'asc'], // Change
        [1, 'desc'] // Change
    ],
    paging: false,
    searching: false,
    info: false,
    bDestroy: true // Add this property to new setting
}

var dt = $('#tableId').DataTable(nTableOptions);
// Or
var dt = $('#tableId').html("").DataTable(nTableOptions);