gpt4 book ai didi

javascript - TinySort - 动画排序示例

转载 作者:行者123 更新时间:2023-11-30 12:51:53 25 4
gpt4 key购买 nike

我正在使用 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>

JS:

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);
}); }

最佳答案

TinySort 可让您设置 your own custom sorting function来处理这样的情况。在函数内部,您可以手动从值中删除名称并仅比较数字。

$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;
}
});

Live Demo

更新:

要回答您在评论中提出的问题,您可以轻松地以不同方式标记您的内容,以便您更轻松地进行更新。例如,您可以将名称和分数包装在 span 中,然后只需更新您的排序函数。

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;
}

Live Demo

理解最重要sorting functions ,这将在你作为程序员的一生中一遍又一遍地帮助你。 ab 只是要比较的两个项目,您的函数应该返回一个比较值,告诉它哪个先于另一个。

TinySort 插件在其文档中告诉您 ab 有几个属性,其中之一是 e,jQuery 对象包含已排序的项目。这意味着您可以使用您需要的任何 jQuery 方法来仅获取您想要比较的项目 - 在您的例子中是分数。

在演示中,我有时在名称之前显示分数,有时在名称之后显示分数,但是您可以看到,当您对它进行排序时,无论如何都会按分数准确排序。

关于javascript - TinySort - 动画排序示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20688969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com