数据表:按列对表进行排序,固定 i++ 值


DataTables: Sorting table by columns, fixed i++ value?

<thead>
 <tr>
  <th class="nosort">#</th>
  <th>Name</th>
  <th>Age</th>
  <th>Location</th>
 </tr>
</thead>
我有表,

我正在使用数据表,所以对列进行排序。我有一个 while 循环,可以生成以下单元格。

# |  Name  | Age| Location
----------------------------
1 | Donald | 37 | Sidney
2 | Janice | 54 | London
3 | Alice  | 44 | California

# 在循环过程中递增 i++。数据表的"nosort"工作正常,我无法单击#。但是,例如,当我单击"名称"时,我想按"名称"对列进行排序,会发生以下情况。

# |  Name  | Age| Location
----------------------------
3 | Alice  | 44 | California
1 | Donald | 37 | Sidney
2 | Janice | 54 | London

如您所见,#"根据名称更改"。我希望使用 i++ 创建的 # 列是固定的,只显示位置,这样当我按名称或年龄排序时它就不会改变。我怎样才能做到这一点?

编辑:我当前的代码

$('#example').dataTable({
   "paging": false,
   "info": false,
   "bFilter":  false,
   "order": [[ 1, "asc" ]],
"columnDefs": [{ "targets": 'nosort' }]
});

我会使用drawCallback来做到这一点:

..
drawCallback: function() {
  $('#example tbody tr').each(function(i, tr) {
    tr.children[0].textContent = i+1;
  })
}
..

演示 -> http://jsfiddle.net/hr8fy3vw/

由于列的内容一直在重置,因此无需通过 API。此外,当使用 jQuery 迭代时,<tr> 的仅可见行将被处理 - 与使用 API 的 every()each()方法相比,可以节省时间。

溶液

请参阅索引列

文章,了解如何添加索引列。

使用以下代码并将example更改为表 ID。

var table = $('#example').DataTable();
table.on( 'order.dt search.dt', function () {
    table.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
        cell.innerHTML = i+1;
    } );
} ).draw();    

演示

请参阅此 jsFiddle 以获取代码和演示。