使用 TableSorter 进行排序和格式化
Sorting and Formatting with TableSorter
我正在尝试格式化由 ajax
不断更新的 table 的一些数据。
我想要浮动数据
变成这样
1.100.500,00 (currency)
整理后
问题是 tablesorter
仅当浮点值采用第一种格式时才能正确排序。我需要做的是:
- 当
ajax
加载数据时,将其显示为(货币),作为货币。
- 点击
table <th>
排序数据时,去掉(currency)货币格式,正确排序数据。
- 正确排序后,重新格式化数据如(货币),为货币。
我已经试过了:(我发现它是 SO 中许多问题的解决方案)
$.tablesorter.addParser({
// set a unique id
id: 'thousands',
is: function(s) {
// return false so this parser is not auto detected
return false;
},
format: function(s) {
// format your data for normalization
return s.replace('.','').replace(/,/g,'');
},
// set type, either numeric or text
type: 'numeric'
});
$("#table_1").tablesorter({
headers: {
2: {//zero-based column index
sorter:'thousands'
}
}
});
但它不起作用。
修复 (demo) 的四件事:
- 替换句点的功能只会删除一个句号。所以改成
.replace(/\./g, "")
(句号也要转义)
- 从字符串中删除
$
- 将
,
替换为小数点,以便正确解析该值。
使用内置 $.tablesorter.formatFloat
函数将值从字符串转换为数字。
$.tablesorter.addParser({
id: 'thousands',
is: function(s) {
return false;
},
format: function(s) {
var number = s.replace(/$/g, '').replace(/\./g, '').replace(/,/g, '.');
return $.tablesorter.formatFloat(number);
},
type: 'numeric'
});
$(function() {
$("table").tablesorter({
theme: 'blue',
headers: {
0: {
sorter: 'thousands'
}
}
});
});
我分享的演示使用的是我的fork of tablesorter,但代码在原始版本中也能正常工作。
我正在尝试格式化由 ajax
不断更新的 table 的一些数据。
我想要浮动数据 变成这样
1.100.500,00 (currency)
整理后
问题是 tablesorter
仅当浮点值采用第一种格式时才能正确排序。我需要做的是:
- 当
ajax
加载数据时,将其显示为(货币),作为货币。 - 点击
table <th>
排序数据时,去掉(currency)货币格式,正确排序数据。 - 正确排序后,重新格式化数据如(货币),为货币。
我已经试过了:(我发现它是 SO 中许多问题的解决方案)
$.tablesorter.addParser({
// set a unique id
id: 'thousands',
is: function(s) {
// return false so this parser is not auto detected
return false;
},
format: function(s) {
// format your data for normalization
return s.replace('.','').replace(/,/g,'');
},
// set type, either numeric or text
type: 'numeric'
});
$("#table_1").tablesorter({
headers: {
2: {//zero-based column index
sorter:'thousands'
}
}
});
但它不起作用。
修复 (demo) 的四件事:
- 替换句点的功能只会删除一个句号。所以改成
.replace(/\./g, "")
(句号也要转义) - 从字符串中删除
$
- 将
,
替换为小数点,以便正确解析该值。 使用内置
$.tablesorter.formatFloat
函数将值从字符串转换为数字。$.tablesorter.addParser({ id: 'thousands', is: function(s) { return false; }, format: function(s) { var number = s.replace(/$/g, '').replace(/\./g, '').replace(/,/g, '.'); return $.tablesorter.formatFloat(number); }, type: 'numeric' }); $(function() { $("table").tablesorter({ theme: 'blue', headers: { 0: { sorter: 'thousands' } } }); });
我分享的演示使用的是我的fork of tablesorter,但代码在原始版本中也能正常工作。