【发布时间】:2011-11-27 09:48:22
【问题描述】:
我在 jquery 中使用 TableSorter 插件。然而,表中的一列如下所列:
市值
- 1200 万美元
- $1.2B
- $3B
- 3400 万美元
并且 TableSorter 无法正常工作。任何想法如何解决它。我可以使用任何其他插件吗?
P.S:我无法取消后缀 M & B。所以我无法在数学上修改市值以使其正常工作。
谢谢
【问题讨论】:
标签: jquery jquery-plugins tablesorter
我在 jquery 中使用 TableSorter 插件。然而,表中的一列如下所列:
并且 TableSorter 无法正常工作。任何想法如何解决它。我可以使用任何其他插件吗?
P.S:我无法取消后缀 M & B。所以我无法在数学上修改市值以使其正常工作。
谢谢
【问题讨论】:
标签: jquery jquery-plugins tablesorter
查看the docs of TableSorter,您似乎可以创建自定义解析器。
创建了这个简单的解析器,它看起来可以解决问题
$.tablesorter.addParser({
// set a unique id
id: 'marketcap',
is: function(s) {
// return false so this parser is not auto detected
return false;
},
format: function(s) {
s = s.replace('$','');
if(s.indexOf('M') >-1){
s = parseInt(s)* 1000000;
}else if(s.indexOf('B') >-1){
s = parseInt(s)* 1000000000;
}
// format your data for normalization
return s;
},
// set type, either numeric or text
type: 'numeric'
});
【讨论】:
阿明的回答很好。也可以与“K”一起使用,或者可以与任何其他度量一起使用。所以完整的例子是:
$.tablesorter.addParser({
// set a unique id
id: 'marketcap',
is: function(s) {
// return false so this parser is not auto detected
return false;
},
format: function(s) {
s = s.replace('$','');
if(s.indexOf('K') >-1){
s = parseInt(s)* 1000;
}else if(s.indexOf('M') >-1){
s = parseInt(s)* 1000000;
}else if(s.indexOf('B') >-1){
s = parseInt(s)* 1000000000;
}
// format your data for normalization
return s;
},
// set type, either numeric or text
type: 'numeric'
});
$(function() {
$("table").tablesorter({
headers: {
3: {
sorter:'marketcap'
}
}
});
});
对于像这样的 html:
<table cellspacing="1" class="tablesorter">
<thead>>
<tr>
<th>english</th>
<th>japanese</th>
<th>calculus</th>
<th>Market Cap</th>
</tr>
</thead>
<tbody>
<tr>
<td>80</td>
<td>70</td>
<td>75</td>
<td>$34M</td>
</tr>
<tr>
<td>90</td>
<td>88</td>
<td>100</td>
<td>$1.2B</td>
</tr>
<tr>
<td>85</td>
<td>95</td>
<td>80</td>
<td>$12M</td>
</tr>
</tbody>
【讨论】:
缺少一些东西! 在上面的示例中,其中一个值是 $1.2B,然后 parseInt(s) 会将其转换为整数。 考虑改用: parseFloat() & toFixed() 考虑小数
$.tablesorter.addParser({
// set a unique id
id: 'marketcap',
is: function(s) {
// return false so this parser is not auto detected
return false;
},
format: function(s) {
s = s.replace('$','');
if(s.indexOf('K') >-1){
s = parseFloat(s).toFixed(3) * 1000;
}else if(s.indexOf('M') >-1){
s = parseFloat(s).toFixed(3) * 1000000;
}else if(s.indexOf('B') >-1){
s = parseFloat(s).toFixed(3) * 1000000000;
}
// format your data for normalization
return s;
},
// set type, either numeric or text
type: 'numeric'
});
$(function() {
$("table").tablesorter({
headers: {
3: {
sorter:'marketcap' // sorting (4th column with parser)
}
}
});
});
【讨论】: