数据表设置默认选项

Datatables setting default options

这是我初始化数据表的方式

$('#example').dataTable( {
  "columnDefs": [ {
      "targets": 0,
      "searchable": false
    } ]
} );

我可以像下面那样做吗?

var mytable = $('#example').dataTable();

mytable.columnDefs({
  "columnDefs": [ {
      "targets": 0,
      "searchable": false
    } ]
} );

这是因为我想在我包含在需要数据表的页面中的 js 文件中定义默认初始化,但仍然能够修改几个选项以便能够自定义每页的一些内容。

我认为这样做的一种可能方法是:

将您的数据初始化table替换为:

var mytable;
function initialiseSpecificDatatable(options) {
    mytable = $('#example').dataTable(options);
    return mytable; // Return table so locally you can use it
}

然后 specify/change 选项

var table = initialiseSpecificDatatable({
    "columnDefs": [{
        "targets": 0,
        "searchable": false
    }]
});

如果您想重新创建 table,您可能需要向创建函数添加 .destroy()。为此,只需添加:

try {
    $(mytable).DataTable().destroy(); //Note capital D to return a DataTable API (See API docs)
} catch (e) {
    // Fails if the table was not a DataTable at the time
}

initialiseSpecificDatatable 函数的开头。

This is what I found for setting defaults, and will be using as a solution to my problem. (Check the use of jquery extend 用于合并对象的内容)

// Disable search and ordering by default
$.extend( $.fn.dataTable.defaults, {
    searching: false,
    ordering:  false
} );

// For this specific table we are going to enable searching except on first (0th) column
// (ordering is still disabled)
$('#example').DataTable( {
    searching: true,
    columnDefs: [{
        "targets": 0,
        "searchable": false
    }]
} );

谢谢