11

我刚开始使用 Christian Bach 的优秀 TableSorter 插件,我需要获取列的当前排序方向。我有几列:

  • ID
  • 姓名
  • 类别

ID 和名称设置为不可排序使用

headers:    { 0: {sorter: false}, 1: {sorter: false} }

我在 Name 上添加了一个单击处理程序,以便它触发 Category 列上的排序事件。使用示例“使用表外的链接对表进行排序”,我可以获取 Name 标题来触发 Category 排序——但它是硬编码的,可以按一个方向排序。

如何让它查看 Category 列当前排序的当前方向,并按相反方向排序?(我可以处理翻转值;由于排序顺序是 0 或 1,我可以对值进行异或运算以得到相反的结果,例如var sort; sort ^= sort;- 我的问题是如何获得当前值。

这是当前在 Name 列上设置点击处理程序的代码:

$("#nameCol").click(function() {
    var sorting = [[2, 0]];     /* sort 3rd col (Category) descending */
    $("#SearchResults").trigger("sorton", [sorting] );  /* SearchResults is the ID of the sortable table */
    return false;               /* cancel default link action on a#nameCol */
});

谢谢!

4

4 回答 4

22

您可以使用内置sortEnd事件来获取 sortOrder,如下所述:https ://stackoverflow.com/a/4150187/363155

$('#yourtableId').on('sortEnd', function(event) {
    // Prints the current sort order to the console
    console.log(event.target.config.sortList);
});
于 2014-01-09T20:51:17.720 回答
10

You can also capture it outside, anywhere else (e.g. in your function, start of ajax, ..), and only when needed and not on every click, with a bit less overhead like this:

lastSortList=$("#mytable")[0].config.sortList;

And example for sorting it back after ajax update:

$("#mytable").trigger("sorton", [lastSortList]);

Remember to declare the first line in the right scope though.

于 2014-07-13T17:44:30.353 回答
3

我写了一个函数来保存当前的排序顺序。这在表格从头开始重建的情况下帮助了我。

function SaveSortOrder(tablename) {
//returns an array of a tablesorter sort order
var hdrorder = new Array();
var hdrs = $("#" + tablename + " th");
var arrayindex = 0;
hdrs.each(function (index) {
    if ($(this).hasClass('headerSortDown')) {
        hdrorder[arrayindex] = [index, 0];
        arrayindex++;
    }
    else if ($(this).hasClass('headerSortUp')) {
        hdrorder[arrayindex] = [index, 1];
        arrayindex++;
    }       
});

return hdrorder;
}
于 2012-05-21T17:49:15.490 回答
1

表头应该都调用相同的点击事件:

$('th').click(function() {
     handleHeaderClick(this);
});  

然后单击处理程序应添加/删除适用的类。

function handleHeaderClick(hdr) {
    if ($(hdr).hasClass('headerSortDown') == true) {
        $(hdr).removeClass('headerSortDown');
        $(hdr).addClass('headerSortUp');
    } else if ($(hdr).hasClass('headerSortUp') == true) {
        $(hdr).removeClass('headerSortUp');
        $(hdr).addClass('headerSortDown');
    } else {
        $('th', myTable).removeClass('headerSortUp headerSortDown');
        $(hdr).addClass('headerSortDown');
    }
    doSomething();
};

我希望这有帮助。

于 2009-12-27T06:41:16.260 回答