jQuery sortElement:按表数据的数值排序 [英] jquery sortElement: sort by numerical value of table data
本文介绍了jQuery sortElement:按表数据的数值排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是 jsFiddle .
从小提琴中可以看到,total
列包含当前按文本排序的数字.
As you can see from the fiddle, the total
column contains numbers that are currently sorted by text.
问:如何按数值对total
列进行排序?
Q: How can I sort the total
column by the numerical value?
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;
});
});
推荐答案
在比较它们之前必须先解析这些值.
You have to parse the values before you compare them.
.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 .
这篇关于jQuery sortElement:按表数据的数值排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文