javascript jQuery 数据表 - 如何以编程方式按列排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31459241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery Datatables - how to programatically sort by a column
提问by SoluableNonagon
So I have a datatable:
所以我有一个数据表:
$(tables[i]).DataTable({
paging: false,
searching: false,
info: false,
ordering: true,
autoWidth: false,
columns: [ ... column stuff here ...
{name: "Name"},
{name: "Account"},
{name: "Number"}
]
});
later in code, I watch for a click event on a button so that I can grab some data from the table and then sort by a column
稍后在代码中,我观察按钮上的单击事件,以便我可以从表中获取一些数据,然后按列排序
var columnName = $('.mySelectBox').val();
var columnNumber = 0;
if(columnName === "Account")
columnNumber = 1;
var table = $(tables[i]).DataTable();
I would like to now sort by either column 0 or column one on this button click. But not on any other column.
我现在想在此按钮单击时按第 0 列或第 1 列排序。但不是在任何其他列上。
//this doesn't work for me
table.sort( [ [columnNumber, 'desc'] ] );
回答by jumojer
I use .order()
instead of .sort()
. Example:
我使用.order()
代替.sort()
. 例子:
$('#dataTables-example').DataTable().order([0, 'desc']).draw();
$('#dataTables-example').DataTable().order([0, 'desc']).draw();
where 0
is the id of the column.
0
列的 id在哪里。
回答by Naren Yellavula
You can easily do that using ordermethod of the table. Youcan adopt the following technique.
您可以使用表格的order方法轻松做到这一点。您可以采用以下技术。
We need to do two things here.
我们需要在这里做两件事。
- Get current column index
- Apply ascending or descending action on particular column on click of a icon
- 获取当前列索引
- 单击图标对特定列应用升序或降序操作
Here let us assume we have a button or link to which clickto bind.
在这里,让我们假设我们有一个按钮或链接,单击可以绑定到该按钮或链接。
$(".arrow-sort-ascending").bind("click", {
// Sorting should happen here
}
Getting column index
获取列索引
I use generic way to get column name. If you are using Jquery, we can fetch the column index using this.
我使用通用方法来获取列名。如果您使用的是 Jquery,我们可以使用它获取列索引。
myColumn = $(parent).prevAll().length
where parentshould be the thof particular column.
其中parent应该是特定列的第 th。
Applying ascending or descending sort
应用升序或降序
// ascending
myTable.order([myColumn, "asc"]).draw()
So if we put the code in a single section, it looks like this.
所以如果我们把代码放在一个单独的部分,它看起来像这样。
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()
}
So whenever we click the arrow-up icon, it sorts the clicked column.
因此,每当我们单击向上箭头图标时,它都会对单击的列进行排序。