簡體   English   中英

jQuery sortElement:按表數據的數值排序

[英]jquery sortElement: sort by numerical value of table data

這是jsFiddle

從小提琴中可以看到, total列包含當前按文本排序的數字。

問:如何按數值對total列進行排序?

var table = $('table');

    $('#facility_header, #city_header, #total')
        .wrapInner('<span title="sort this column"/>')
        .each(function(){

            var th = $(this),
                thIndex = th.index(),
                inverse = false;

            th.click(function(){

                table.find('td').filter(function(){

                    return $(this).index() === thIndex;

                }).sortElements(function(a, b){

                    return $.text([a]) > $.text([b]) ?
                        inverse ? -1 : 1
                        : inverse ? 1 : -1;

                }, function(){

                    // parentNode is the element we want to move
                    return this.parentNode; 

                });

                inverse = !inverse;

            });

        });

在比較它們之前,您必須先解析這些值。

.sortElements(function(a, b){
    var sa = $.text([a]);
    var sb = $.text([b]);

    var ia = parseInt(sa);
    var ib = parseInt(sb);

    if (!isNaN(ia) && !isNaN(ib)) {
        return ia > ib ? (inverse ? -1 : 1) : (inverse ? 1 : -1);
    }

    return sa > sb ? (inverse ? -1 : 1) : (inverse ? 1 : -1);
}

這是您更新的jsfiddle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM