jQuery Datatables – 如何按列进行编程排序
所以我有一个数据表:
$(tables[i]).DataTable({ paging: false, searching: false, info: false, ordering: true, autoWidth: false, columns: [ ... column stuff here ... {name: "Name"}, {name: "Account"}, {name: "Number"} ] });
稍后在代码中,我会在按钮上查看单击事件,以便我可以从表中获取一些数据,然后按列进行排序
var columnName = $('.mySelectBox').val(); var columnNumber = 0; if(columnName === "Account") columnNumber = 1; var table = $(tables[i]).DataTable();
我想现在按此按钮单击第0列或第1列排序。 但不是任何其他专栏。
//this doesn't work for me table.sort( [ [columnNumber, 'desc'] ] );
我使用.order()
而不是.sort()
。 例:
$('#dataTables-example').DataTable().order([0, 'desc']).draw();
其中0
是列的id。
您可以使用表格的顺序方法轻松完成此操作。 您可以采用以下技术。
我们需要在这里做两件事。
- 获取当前列索引
- 单击图标,在特定列上应用升序或降序操作
这里让我们假设我们有一个按钮或链接点击绑定。
$(".arrow-sort-ascending").bind("click", { // Sorting should happen here }
获取列索引
我使用通用方法获取列名。 如果您使用的是Jquery,我们可以使用此方法获取列索引。
myColumn = $(parent).prevAll().length
其中parent应该是特定列的th 。
应用升序或降序排序
// ascending myTable.order([myColumn, "asc"]).draw()
因此,如果我们将代码放在一个部分中,它看起来就像这样。
table = myTable // This is datatable you initialized $(".arrow-sort-ascending").bind("click", {table: table}, function(event){ parent = $(event.target).parent() myIndex = $(parent).prevAll().length; table.order([myIndex, "asc"]).draw() }
因此,每当我们单击向上箭头图标时,它会对单击的列进行排序。