sort table by price column

前端 未结 5 836
野趣味
野趣味 2021-01-23 20:44

It\'s the billing list:

Service   Price
---------------
S1        13 CHF
S2        Free
S3        Free
S4        40 CHF

I want to sort it by pr

5条回答
  •  醉梦人生
    2021-01-23 21:04

    Because you have custom, non-numeric values to sort, you will need some sort of custom sort function. Here's such a custom sort routine for your table:

    HTML:

    ServicePrice
    S113 CHF
    S2Free
    S3Free
    S440 CHF

    Code:

    $(".sortBy").click(function() {
        var self = $(this);
        var tbody = self.closest("tbody");
    
        // determine which column was clicked on
        var column = self.index();
    
        // get the sort type for this column
        var sortType = self.data("sortType");
        var sortCells = [];
    
        // get all rows other than the clicked on row
        //    find the right column in that row and
        //    get the sort key from it
        $(this).closest("tr").siblings().each(function() {
            var item = $(this).find("td").eq(column);
            var val = item.text();
            var matches;
            if (sortType == "numeric") {
                if (val.toLowerCase() == "free") {
                    val = 0;
                } else {
                    val = parseInt(val, 10);
                }
            } else {
                // find numbers in the cell
                matches = val.match(/\d+/);
                if (matches) {
                    val = parseInt(matches[0], 10);
                } else {
                    val = 0;
                }
            }
            sortCells.push({cell: item, data: val});
        });
        // sort by the key
        sortCells.sort(function(a, b) {
            return(a.data - b.data);
        });
        // reinsert into the table in sorted order
        for (var i = 0; i < sortCells.length; i++) {
            sortCells[i].cell.parent().appendTo(tbody);
        }
    });
    

    Working demo: http://jsfiddle.net/jfriend00/3w9gQ/

提交回复
热议问题