本文介绍了在 div 标签和 jQuery 中按数字对 div 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 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 按最高数字排序到最低数字.我该怎么办?感谢您的任何指导!我想我应该补充一点,排序应该发生在页面加载上.:)

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 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 16:41
查看更多