在div标签和jQuery中按数字排序div

Rob*_*t E 3 sorting jquery numbers

我正在尝试使用jQuery对div列表进行排序.基本上,列表可能如下所示:

<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>
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用一些jQuery自动将div按最高数量排序到最低.我怎么能这样做?谢谢你的任何指导!猜猜我应该补充说,排序应该发生在pageload上.:)

Ili*_*a G 13

我为此目的写了一个小插件.随意偷.基本上,您可以选择元素,对它们进行排序,并在新的顺序中重新使用.

================================================== ============================

Per Jason的请求包括此处的代码

$(".contest_entry").orderBy(function() {return +$(this).text();}).appendTo("#parent_div");
Run Code Online (Sandbox Code Playgroud)

#parent_div.contest_entrys 的容器.

+只是一种偷偷摸摸的方式将值转换为数字强制数字比较而不是字符串比较(除非这是你想要的).

orderBy()是我写的一个排序插件.从那时起我对它进行了一些安静的扩展,但这是简单的版本:

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;
    });
};
Run Code Online (Sandbox Code Playgroud)