没有初始数据时如何为我的单元格设置默认属性

How do I set the default attributes for my cells when there is no initial data

我有一个场景,我根据通过 websocket 接收的数据填充我的数据 table。所以我想最好的方法是在 html 中创建一个空的 table,然后通过 API.

添加数据

所以说我希望我的最终 table 看起来像这样:

<table id="example" class="display" style="width:100%">
    <thead>
        <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td class="name">Tiger Nixon</td>
            <td class="position">System Architect</td>
            <td class="office">Edinburgh</td>
            <td class="age">61</td>
            <td class="start-date">2011/04/25</td>
            <td class="salary">0,800</td>
        </tr>
        <tr>
            <td class="name">Garrett Winters</td>
            <td class="position">Accountant</td>
            <td class="office">Tokyo</td>
            <td class="age">63</td>
            <td class="start-date">2011/07/25</td>
            <td class="salary">0,750</td>
        </tr>
    </tbody>
</table>

动态加载我的 table 时,我只会定义第一部分:

<table id="example" class="display" style="width:100%">
    <thead>
        <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
        </tr>
    </thead>
</table>

然后在收到数据后在我的 javascript 中调用 row.add()

但是我如何以这种方式为我的列单元格设置默认值 类?

当您使用 row.add() 时,return 值为新创建(但尚未显示)的行。

您可以使用此值遍历行中的单元格,其中可以添加 class 个名称。最后你可以绘制行,所以它显示了。

下面显示了基本方法,其中我们有一个预定义数组,其中包含您要处理的 class 个名称:

  $(document).ready(function() {
  
    var classNames = [ 'name', 'position' ];
 
    var table = $('#example').DataTable();
    
    var row = table.row.add( ['Quinn Flynn', 'Accountant'] );
    var i = 0;
    row.cells().every( function () {
    var node = this.node();
      $( node ).addClass( classNames[i++] );
    } );
    row.draw();

  });

在您的例子中,从创建行到绘制行的最后一段代码将放在一个函数中。

这将生成一个 HTML 正文,如下所示:

<tbody>
    <tr role="row" class="odd">
        <td class="name sorting_1">Quinn Flynn</td>
        <td class="position">Accountant</td>
    </tr>
</tbody>