首页 > 解决方案 > 具有可变数量表头的 DataTables 渲染函数

问题描述

我知道,使用 DataTables 时,表头列和表数据列的数量需要相同。
我的问题是我现在面临的问题是我的<th>标签数量有条件地 +/- 2 并且我正在使用渲染函数来显示相应的列<td>
DataTables 在那个 ( Cannot read property 'style' of undefined) 上抛出错误并不奇怪。
无论如何,我既没有看到摆脱渲染功能的机会,也没有看到静态渲染表格标题的机会。
当特定列没有表头时,有没有办法统计 DataTables?

columns: [
   {
   data: "some_id",
   render: function (data, type, row) {
      return "some content";
   },
   {
    data: "some_id", 
    render: function (data, type, row) {
       return "some content";
   }
]

这是造成麻烦的部分。

标签: javascriptdatatables

解决方案


DataTables requires the amount of columns in the <thead> to match the column count in the <tbody>. Adding columns in the column:[] array that don't have a associated column in the <thead> will produce a internal DataTable JS error. This can be worked around by adding an empty <th></th> in the header for columns that are using the render.

<table>
     <thead>
          <th>Column 1</th>
          <th>Column 2</th>
          <th></th>
     </thead>
</table> 

DataTable columns property

columns: [
   {data: "column1"},
   {data: "column2"},
   {
         data: "some_id", 
         render: function (data, type, row) {
            return "some content";
         },
         sortable: false, // optional
         searchable: false // optional
   }
]

As an additional tip, it may be beneficial to add sortable, searchable false along with the render when adding items in, such as, a button through the render. This will avoid problems with the user potentially trying to sort or search on a column that is display only or has an actionable item that is not available for search and sort.


推荐阅读