数据表:如何将类设置为表行单元格(但不是表标题单元格!

DataTables: How to set classes to table row cells (but not to table header cells!)

本文关键字:单元格 标题 设置 数据表      更新时间:2023-09-26

我的桌子风格非常好。

{对不起链接不再工作}

我必须添加 sClass,以便新行(由 fnAddData 添加)获得正确的类。

不幸的是,这破坏了我的布局,因为这些类也被添加到我的表头单元格中!

{对不起链接不再工作}

如何将sClass配置为仅申请TBODY细胞?

澄清一下:

  var rolesTable = $('#roles').dataTable({
      "aoColumns": [
        { "mDataProp": "id", "sClass": "avo-lime-h avo-heading-white" },
        { "mDataProp": "name", "sClass": "avo-light" },
        { "mDataProp": "module", "sClass": "avo-light" },
        { "mDataProp": "description", "sClass": "avo-light" },
        { "mDataProp": null, "bSearchable": false, "bSortable": false, 
          "sDefaultContent": '<button type="button" name="add" class="btn"><i class="icon-plus icon-white"></i></button>' }, 
      ],
  }); // end od dataTable

这样当我打电话时

rolesTable.fnAddData( { 
    "id": 10, 
    "name": "testname", 
    "module": "testmodule", 
    "description": "testdescription" 
} );

然后添加的行如下所示:

<tr>
    <td class="avo-lime-h avo-heading-white">10</td>
    <td class="avo-light">testname</td>
    <td class="avo-light">testmodule</td>
    <td class="avo-light">testdescription</td>
    <td></td>
</tr>

这完全没问题

**

问题是 ** 此设置还会将这些类添加到:

<thead>
    <tr> (...) </tr>
</thead>

表头细胞...我不想要的

我的问题的解决方案是:使用 fnRowCallback 而不是 sClass 将类设置为新行。

  var rolesTable = $('#roles').dataTable({
      "aoColumns": [
        { "mDataProp": "id" },
        { "mDataProp": "name" },
        { "mDataProp": "module" },
        { "mDataProp": "description" },
        { "mDataProp": null, "bSearchable": false, "bSortable": false, 
          "sDefaultContent": '<button type="button" name="add" class="btn btn-round"><i class="icon-plus icon-white"></i></button>' }, 
      ],
      "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
          $('td:eq(0)', nRow).addClass( "avo-lime-h avo-heading-white" );
          $('td:eq(1),td:eq(2),td:eq(3)', nRow).addClass( "avo-light" );
        }
  }); // end od dataTable

由于您只使用 sClass 将样式应用于表格,因此解决问题的简单方法是修改 CSS 本身以仅应用于 td 元素。

旧的 CSS 样式:

.avo-light {
    color: blue;
}

新的 CSS 样式:

td.avo-light {
    color: blue;
}

这样,CSS 只会影响您有兴趣应用样式的单元格,尽管 sClass 也应用于 th 元素。

我意识到这个问题有点老了,但我发现它比最佳解决方案更具模块化。

之前设置默认类。

$.fn.dataTableExt.oStdClasses.sStripeOdd = '';
$.fn.dataTableExt.oStdClasses.sStripeEven = '';

有关更多参考,请参见此处http://www.datatables.net/styling/custom_classes

  let table = $("#myTable").dataTable();
  table.rows().every(function(rowIdx, tableLoop, rowLoop){
    $(this.node().cells[0]).addClass('red');
    $(this.node().cells[1]).addClass('blue');
  }

呈现表后,使用每行的 JavaScript 选择器遍历所有行,并进行所需的任何更改。这解决了gamliela在loostr的回答中提出的性能问题。DataTables rows().every() 文档