繁体   English   中英

使用jQuery对列表进行数字排序,然后按字母顺序排序?

[英]Sort list numerally and then alphabetically using jQuery?

http://jsbin.com/aboca3/95/edit

这是单独的数字和字母排序的工作示例。

它运作良好,问题是,它不会按字母顺序对具有相同<em>数字的项目进行排序。

例如,按数字排序给出了Salpinestars(58),Joe Rocket(58)。 应该给相反的顺序。

我试图更改items.sort(sortEm).prependTo(self); items.sort(sortAlpha).sort(sortEm).prependTo(self); ,但无效。

有什么想法吗?

使用以下sortEm():

function sortEm(a,b){
  var emA = parseInt($('em',a).text().replace(/[\(\)]/g,''));
  var emB = parseInt($('em',b).text().replace(/[\(\)]/g,''));
  if (emA == emB) { // sort alphabetically if em number are equal
    return sortAlpha(a,b);
  }
  return emA < emB ? 1 : -1;
}

您可以编写一个函数以按两个条件排序。

// ORDER BY EmValue, LiMinusEmText

function sortBoth(a, b) {
    var aText = $(a).text().replace(/\(\d+\)\s*$/, "");      // chop off the bracket
    var bText = $(b).text().replace(/\(\d+\)\s*$/, "");      // and numbers portion
    var aValue = +$(a).find("em").text().replace(/\D/g, ""); // parse out em value
    var bValue = +$(b).find("em").text().replace(/\D/g, ""); // and convert to number
    if (aValue == bValue) {
        if (aText == bText) {
            return 0;
        }
        else if (aText < bText) {
            return -1;
        }
        else /*if (aText > bText)*/ {
            return 1;
        }
    }
    else {
        return aValue - bValue;
    }
}

// ORDER BY LiMinusEmText, EmValue

function sortBoth(a, b) {
    var aText = $(a).text().replace(/\(\d+\)\s*$/, "");      // chop off the bracket
    var bText = $(b).text().replace(/\(\d+\)\s*$/, "");      // and numbers portion
    var aValue = +$(a).find("em").text().replace(/\D/g, ""); // parse out em value
    var bValue = +$(b).find("em").text().replace(/\D/g, ""); // and convert to number
    if (aText == bText) {                                    // strings value same?
        return aValue - bValue;                              // then return a - b
    }
    else if (aText < bText) {
        return -1;
    }
    else /*if (aText > bText)*/ {
        return 1;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM