组排序JQuery列表元素

Group sorting JQuery list elements

本文关键字:列表元素 JQuery 排序      更新时间:2023-09-26

我想根据它的组对列表元素进行排序。

例如:

:

  • 苹果-水果
  • 香蕉-水果
  • 酸弹-糖果
  • 葡萄-水果
  • 蔓越莓-水果
  • 巧克力-糖果

将成为:

  • 苹果-水果
  • 香蕉-水果
  • 蔓越莓-水果
  • 葡萄-水果
  • 巧克力-糖果
  • 酸弹-糖果

按字母顺序排列,Fruit的组项首先排序,然后是Sweets。

我不太确定如何使这两种排序都是正确的。例如,我试着对食物进行分类,但是这个组不会被分类。

function sorting() {
function sortASC(a, b) {
    return $(b).find(".group").text() < $(a).find(".group").text();
}
$("li").sort(sortASC).appendTo('ul');
}

您可以将其全部构建到一个排序函数中:

function sortASC(a, b) {
    // Cache Text
    var a_group = $(a).find(".group").text(),
        a_item = $(a).find(".item").text(),
        b_group = $(b).find(".group").text(),
        b_item = $(b).find(".item").text()
    return (
        b_group < a_group            // If group is bigger
        || (                         // OR
            b_group == a_group       // If groups are same
            && b_item < a_item       // AND item is bigger
        )
    );
}

例子小提琴