我用TinySort做了一个排行榜/高分,当我只有数字的时候,它是完美的,它是正确排序的。当然,我需要在每个分数前面加上一个名字,所以当我这样做的时候,它会按字母顺序排序,因为有字符。
注意:我使用的是这个插件的动画排序:http://tinysort.sjeiti.com/
下面是代码: HTML:
<ol id="xanim" class="xmpl">
<li id="high1">34</li>
<li id="high2" >3334</li>
<li id="high3">344</li>
<li id="high4">3244</li>
<li id="high5">3345</li>
<li id="high6">345</li>
<li id="high7">35</li>
<li id="high8">0</li>
<li id="high9">0</li>
<li id="high10">0</li>
</ol>
<button onclick="sortHighscore()">sort</button>联署材料:
function sortHighscore(){
$.tinysort.defaults.order = 'desc';
var $Ul = $('ol#xanim');
$Ul.css({position:'relative',height:$Ul.height(),display:'block'});
var iLnH;
var $Li = $('ol#xanim>li');
$Li.each(function(i,el){
var iY = $(el).position().top;
$.data(el,'h',iY);
if (i===1) iLnH = iY;
});
$Li.tsort().each(function(i,el){
var $El = $(el);
var iFr = $.data(el,'h');
var iTo = i*iLnH;
$El.css({position:'absolute',top:iFr}).animate({top:iTo},500);
}); }发布于 2013-12-19 20:36:26
TinySort允许您设置您自己的自定义排序功能来处理这样的情况。在函数内部,您可以手动从值中删除名称,并只比较数字。
$Li.tsort({
sortFunction: function (a, b) {
// Remove the text from your item, leaving only the numbers
var aNum = a.e.text().split(' ')[1];
var bNum = b.e.text().split(' ')[1];
return bNum - aNum;
}
});现场演示
更新:
要回答你在评论中提出的问题,你可以很容易地用不同的方式标记你的内容,从而使你更容易更新。例如,您可以将名称和分数封装在spans中,然后只更新排序函数。
sortFunction: function (a, b) {
// Perform whatever logic we need to go from the items to be sorted (the list items)
// to the text we actually want to compare (scores)
var aNum = a.e.find('.score').text();
var bNum = b.e.find('.score').text();
// Return a comparison of the scores
return bNum - aNum;
}现场演示
最重要的是理解排序函数,它将帮助您作为程序员一而再、再而三地帮助您。a和b只是两个要比较的项目,您的函数应该返回一个比较,告诉它哪个应该放在另一个前面。
TinySort插件在其文档中告诉您,a和b有几个属性,其中一个属性是e,它是包含排序项的jQuery对象。这意味着你可以使用任何jQuery方法,你只需要得到你想要比较的项目--在你的例子中,就是分数。
在演示中,我有分数有时在名称之前,有时在后面,但您可以看到,当您排序时,所有这些都被准确地按分数排序。
https://stackoverflow.com/questions/20688969
复制相似问题