我目前正在研究奥运会的替代奖牌数,并使用表格排序器插件让用户能够从不同角度查看数据。
我坚持这一点,即行的正确顺序:如果两个国家的金牌数量相同,你看看银牌。银牌较多的国家获得第一名,银牌较少的国家获得第二名。
如何在表格分类器的帮助下实现这一目标?
您可以在 http://www.benedictzinke.de/olympia 查看源代码
到目前为止,它是按每 10 名运动员的金牌排序的。对于至少获得一枚金牌的国家来说,这一切都很好。但是一排排没有金牌的国家搞砸了。
我认为最简单的解决方案是在奖牌列中隐藏加权奖牌值。
例如,让我们看看韩国与罗马尼亚。我在括号中包含了加权值,这些值基本上是每种类型的奖牌的数量,包括前导零(所以"2"变成了"002")
Country G (gggsssbbb) S (sssgggbbb) B (bbbgggsss)
Korea 12 (012005006) 5 (005012006) 6 (006012005)
Romania 2 (002005002) 5 (005002002) 2 (002012002)
现在,如果我们对银牌列进行排序,您将看到韩国的005012006
大于罗马尼亚的005002002
,并将韩国排序在罗马尼亚之前。
现在,对于在我们调用tablesorter之前设置这一切的代码,以及一个演示
$('#medal_count').find('tbody tr').each(function(){
var pref = '<span style="display:none">', // span that hides the weighted value
suff = '</span>',
$t = $(this),
$c = $t.children(),
gold = ("000" + $c.eq(4).text()).slice(-3), // add leading zeros
silver = ("000" + $c.eq(5).text()).slice(-3),
bronze = ("000" + $c.eq(6).text()).slice(-3);
// add hidden weighted medal values
$c.eq(4).prepend(pref + gold + silver + bronze + suff);
$c.eq(5).prepend(pref + silver + gold + bronze + suff);
$c.eq(6).prepend(pref + bronze + gold + silver + suff);
});
$("#medal_count").tablesorter({
textExtraction : function(node){
var $n = $(node);
// only return the weighted values if a span exists
return ($n.find('span').length) ?
$n.find('span').text() :
$n.text();
},
sortList: [[8, 1]]
});
使用tablesorter插件,您应该参考有关编写自己的解析器的文档。在这里看到它: http://tablesorter.com/docs/example-parsers.html
您所要求的内容似乎几乎完全符合文档中使用的示例。为方便起见,下面复制了文档中的代码。
// add parser through the tablesorter addParser method
$.tablesorter.addParser({
// set a unique id
id: 'grades',
is: function(s) {
// return false so this parser is not auto detected
return false;
},
format: function(s) {
// format your data for normalization
return s.toLowerCase().replace(/good/,2).replace(/medium/,1).replace(/bad/,0);
},
// set type, either numeric or text
type: 'numeric'
});
$(function() {
$("table").tablesorter({
headers: {
6: {
sorter:'grades'
}
}
});
});
出于您的目的,代码将如下所示:
// add parser through the tablesorter addParser method
$.tablesorter.addParser({
// set a unique id
id: 'medals',
is: function(s) {
// return false so this parser is not auto detected
return false;
},
format: function(s) {
// format your data for normalization
// Note the 'i' added after the medal type, that makes it case insensitive.
return s.toLowerCase().replace(/gold/i,2).replace(/silver/i,1).replace(/bronze/i,0);
},
// set type, either numeric or text
type: 'numeric'
});
$(function() {
$("table").tablesorter({
headers: {
6: { // Replace '6' with the number of the column that your medals are in
sorter:'medals'
}
}
});
});