HTML中单击Table表头实现排序

来源:互联网 发布:手机魔术拍照软件 编辑:程序博客网 时间:2024/05/04 20:56

本代码基于jquery,如下:

<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"type="text/javascript"></script>

/*    * The object TableSort can be used as a tool class    */var TableSort = {    init: function (TableId) {        this.setDataArray(TableId);        this.table = $("#" + TableId);        $("#" + TableId + " tr:first td").bind("click",this.sort);    },    table:null,    dataArray: [],    htmlArray: {},    setDataArray: function (TableId) {        $("#" + TableId + " tr").each(function (i) {            var tr = $(this);            if (i != 0) {                var temp = [];                temp.push(tr.attr("rowid"));                tr.find("td").each(function () {                    temp.push($(this).text());                });                TableSort.dataArray.push(temp);                TableSort.htmlArray[tr.attr("rowid")] = tr.clone();            }        });    },    sort: function () {        var td = $(this);        var index = td.index();        var sortIndex = index + 1;        var currentSort = td.attr("sortType") || "ASC";                     if (currentSort == "ASC") {            TableSort.dataArray = TableSort.multiArraySort(TableSort.dataArray, "DESC", sortIndex);            td.attr("sortType", "DESC");        } else {            TableSort.dataArray = TableSort.multiArraySort(TableSort.dataArray, "ASC", sortIndex);            td.attr("sortType", "ASC");        }        td.siblings().attr("sortType", "");                            //refresh the table        TableSort.table.find("tr:gt(0)").remove();        for (var i = 0, len = TableSort.dataArray.length; i < len; i++) {            var rowid = TableSort.dataArray[i][0];            TableSort.table.children().append(TableSort.htmlArray[rowid]);        }                        },    multiArraySort: function (array, type, index) {        var resultArray = array;        if(type == "ASC"){            resultArray.sort(function (a, b) {                //String is the default type of content,the number should return b[sortIndex]-a[sortIndex].                return a[index].localeCompare(b[index]);            });            return resultArray;        } else if (type == "DESC") {            resultArray.sort(function (a, b) {                return b[index].localeCompare(a[index]);            });            return resultArray;        } else {            console.log("The argument of 'multiArraySort' value does not match the type that this argument expects. " +                        "Check that the argument value is appropriate to the type expected by this argument, and then try again.");            return null;        }    }};

使用时直接如下调用:

TableSort.init("tableId");




0 0