how to get current sort order from tablesorter plugin?

本秂侑毒 提交于 2019-11-29 06:30:41
Les Green

The table headers should all call the same click event:

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

Then click handler should add/remove the applicable classes.

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();
};

I hope this helps.

You can use the built in sortEnd event to get the sortOrder as explained here: 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);
});

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.

I wrote a function to save the current sort order. This helped me out in a situation where the table was being rebuilt from scratch.

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!