在cookie中保存tablesorter选项

时间:2011-10-13 09:25:22

标签: jquery cookies tablesorter

我正在使用jQuery Tablesorter插件对表进行排序,并希望使用jquery cookie插件将选项保存在cookie中。

有人做过这样的事吗?或者会知道怎么做?

我使用click()事件进行排序,因为我的表格被分成几部分,例如:

function setupTablesorter() {
    var currentSort;
    var cookieSortList = $.evalJSON($.cookie("table_sort_list"));
    if (cookieSortList == null)
        cookieSortList = [[1, 0]]

    $('table').each(function (i, e) {
        var myHeaders = {}
        $(this).find('th.nosort').each(function (i, e) {
            myHeaders[$(this).index()] = { sorter: false };
        });
        $(this).tablesorter({ sortList: cookieSortList, widgets: ['zebra'], headers: myHeaders }).bind("sortEnd", function (sorter) {
            currentSort = sorter.target.config.sortList;
        });
    });

    $(".uiGridHeader th").click(function () {
        $.cookie("table_sort_list", $.toJSON(currentSort));
    });

    console.log(currentSort);
}

function setupFixedHeader() {

    var copyThead = $(".uiGridContent thead").html();
    var copyCol = $(".uiGridContent colgroup").html();
    copyThead = '<table>' + copyCol + '<thead>' + copyThead + '</thead></table>';
    $(".uiGridHeader").html(copyThead);
    $(".uiGridContent table").tablesorter();
    $(".uiGridContent table thead").hide();
    function bindClick() {
        $(".uiGridHeader th").click(theadClick);
    }
    var direction = 0;
    function theadClick() {
        console.log('click');
        if (direction) {
            direction = 0;
        } else {
            direction = 1;
        }
        var index = $(this).index();
        var sorting = [[index, direction]];

        $(".uiGridContent table").trigger("sorton", [sorting]);

        var FindcopyThead = $(".uiGridContent thead").html();
        var FindcopyCol = $(".uiGridContent colgroup").html();
        var NewcopyThead = '<table>' + FindcopyCol + '<thead>' + FindcopyThead + '</thead></table>';
        $(".uiGridHeader").html(NewcopyThead);
        bindClick();
    }
    bindClick();
}

因此我需要在函数中的某个位置记录cookie中的选项。

2 个答案:

答案 0 :(得分:1)

在您的功能中,您可以在$.cookie("table_sort_list", sorting);

之后添加var sorting

并且在您启动表格的功能中,您可以执行类似

的操作
var cookieSortList= $.cookie("table_sort_list");
if(cookieSortList== null)
    cookieSortList = []

$("table").tablesorter({ 
    sortList: cookieSortList
}); 

另一种,也许更好的方法是获得jQuery tablesorter how to find sortList object

中描述的新排序

答案 1 :(得分:0)

如果您想要保存排序以便可以在将来访问时对表进行重新排序,那么现在在Tablesorter中内置了saveSort选项,该选项使用本地存储(以及cookie作为后备)。有关详细信息,请参阅this answer