如何重用数据表选项

时间:2019-01-15 12:26:15

标签: javascript datatables

我想为数据表创建一个动态系统。

我有这段代码,在其中我归因于DataTable主要选项类“ my-datatable”的所有元素。接下来,我想为特定的数据表添加选项。

    $(".my-datatable").DataTable({
      responsive: true,
      dom: 'Bfrtip',
      buttons: [
           'csv',
           'excel',
           'pdf',
      ],
      "language": {
           "search": "",
           "searchPlaceholder": "Search for any client’s information…",
           "emptyTable": "No data available in table",
           "info": "",
           "infoEmpty": "Showing 0 to 0 of 0 entries",
           "infoFiltered": "(filtered from _MAX_ total entries)",
           "lengthMenu": "Show _MENU_ entries",
           "loadingRecords": "Loading...",
           "processing": "Processing...",
           "zeroRecords": "No matching records found",
      },
});


$(".my-datatable#specific-datatable").DataTable({
      "order": [[ 1, "asc" ]],
      columnDefs: [
           { targets: [0,2,4,5,7], orderable: false },
      ],
      "columns": [
           { "width": "5%" },
           { "width": "20%" },
           { "width": "10%" },
           { "width": "5%" },
           { "width": "20%" },
           { "width": "10%" },
           { "width": "15%" },
           { "width": "20%" },
      ]
});

1 个答案:

答案 0 :(得分:0)

在这种情况下可以应用

$.extend。在声明了第一个表的选项之后,使用$.extend通过该选项扩展特定的表属性,如下所示:

var originalTableOption = {
      responsive: true,
      dom: 'Bfrtip',
      buttons: [
           'csv',
           'excel',
           'pdf',
      ],
      "language": {
           "search": "",
           "searchPlaceholder": "Search for any client’s information…",
           "emptyTable": "No data available in table",
           "info": "",
           "infoEmpty": "Showing 0 to 0 of 0 entries",
           "infoFiltered": "(filtered from _MAX_ total entries)",
           "lengthMenu": "Show _MENU_ entries",
           "loadingRecords": "Loading...",
           "processing": "Processing...",
           "zeroRecords": "No matching records found",
      },
};
$(".my-datatable").DataTable(originalTableOption);

var specificTableOnlyOption = {
      "order": [[ 1, "asc" ]],
      columnDefs: [
           { targets: [0,2,4,5,7], orderable: false },
      ],
      "columns": [
           { "width": "5%" },
           { "width": "20%" },
           { "width": "10%" },
           { "width": "5%" },
           { "width": "20%" },
           { "width": "10%" },
           { "width": "15%" },
           { "width": "20%" },
      ]
};
var specificTableOption = $.extend(specificTableOnlyOption, originalTableOption);
$(".my-datatable#specific-datatable").DataTable(specificTableOption);