在div标签和jQuery中按数字对div进行排序 [英] Sorting divs by number inside div tag and jQuery
问题描述
我正在尝试使用jQuery对div列表进行排序.本质上,列表可能看起来像这样:
I'm trying to sort a list of divs with jQuery. Essentially the list might look like this:
<div class="contest_entry"><img src="image.png" /><span class="votes">14</span></div>
<div class="contest_entry"><img src="image.png" /><span class="votes">8</span></div>
<div class="contest_entry"><img src="image.png" /><span class="votes">2</span></div>
<div class="contest_entry"><img src="image.png" /><span class="votes">2</span></div>
<div class="contest_entry"><img src="image.png" /><span class="votes">2</span></div>
<div class="contest_entry"><img src="image.png" /><span class="votes">21</span></div>
我正在尝试使用一些jQuery自动按照最高编号到最低编号对div进行排序.我该怎么办?感谢您的指示!猜猜我应该补充说排序应该发生在pageload上. :)
I'm trying to use some jQuery to automatically sort the divs by highest number to lowest. How could I go about this? Thanks for any direction! Guess I should add that the sort should happen on pageload. :)
推荐答案
我写了一个小插件只是为了这个目的.随时偷. 基本上,您可以选择元素,对元素进行排序,然后以新的顺序重新添加.
I wrote a small plugin just for this purpose. Feel free to steal. Basically you select elements, sort them, and reappend in the new order.
================================================ ==============================
==============================================================================
应Jason的要求,包括此处的代码
Per Jason's request including code here
$(".contest_entry").orderBy(function() {return +$(this).text();}).appendTo("#parent_div");
#parent_div
是.contest_entry
的容器.
+
只是一种将值转换为数字以强制进行数字比较而不是字符串比较的偷偷摸摸的方法(除非您要这样做).
The +
is just a sneaky way to convert value to number to force number compare rather than string compare (unless that is what you want).
orderBy()
是我编写的排序插件.从那时起,我在安静的地方进行了扩展,但这是简单的版本:
orderBy()
is a sorting plugin that I wrote. I expanded on it quiet a bit since then, but here is the simple version:
jQuery.fn.orderBy = function(keySelector)
{
return this.sort(function(a,b)
{
a = keySelector.apply(a);
b = keySelector.apply(b);
if (a > b)
return 1;
if (a < b)
return -1;
return 0;
});
};
这篇关于在div标签和jQuery中按数字对div进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!