繁体   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