sort table by price column

前端 未结 5 882
野趣味
野趣味 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:16

    Here is some custom sort code that will work for you assuming the following:

    1. Your table has the id of items
    2. Each row (tr) you want sorted have the class item
    3. Each price cell (td) has the class price

    Then just include the following jQuery code and call the function when you want to sort: (Here is a demo)

    var sorted_by_price = false;
    
    function sortByPrice() {
        $('#items').append(
            $('#items').find('tr.item').sort(function (a, b) {
                var td_a = $($(a).find('td.price')[0]);
                var td_b = $($(b).find('td.price')[0]);
                if(sorted_by_price){
                    if(td_a.html() == 'Free') return 1;
                    return td_b.html().replace(/\D/g, '') - td_a.html().replace(/\D/g, '');
                }else{
                    if(td_a.html() == 'Free') return -1;
                    return td_a.html().replace(/\D/g, '') - td_b.html().replace(/\D/g, '');
                }
            })
        );
        if(sorted_by_price) sorted_by_price = false;
        else sorted_by_price = true;
    }
    

提交回复
热议问题