Jquery排序功能不工作

jquery sorting function not working

本文关键字:工作 功能 排序 Jquery      更新时间:2023-09-26

下面的排序函数不适合我:

function sortTags() {
    var options = $('#ddlTags option').sort(tags_asc_sort);
    $("#ddlTags").empty().append(options);
    function tags_asc_sort(a, b) {
        var aText = $(a).text().toUpperCase();
        var bText = $(b).text().toUpperCase();
        var compare = aText < bText ? -1 : 1;
    }
}

我对一个不同的ddl使用了类似的函数,它按预期工作。知道是什么问题吗?

基于前面的答案,并尝试更纯粹,我将尝试使用这个排序器,它使用LocaleCompare方法。

function tags_asc_sort(a, b) {
    var aText = $(a).text().toUpperCase();
    var bText = $(b).text().toUpperCase();
    return aText.localeCompare(bText);
}

var text = 'hello this is test text hello'.split(' ');
    function tags_asc_sort(a, b) {
        var aText = a.toUpperCase();
        var bText = b.toUpperCase();
        return aText.localeCompare(bText);
    }
    console.log(text.sort(tags_asc_sort));

您需要返回compare以便排序工作。

function sortTags() {
  var options = $('#ddlTags option').sort(tags_asc_sort);
  $("#ddlTags").empty().append(options);
  function tags_asc_sort(a, b) {
    var aText = $(a).text().toUpperCase();
    var bText = $(b).text().toUpperCase();
    var compare = aText < bText ? -1 : 1;
    return compare;
  }
}
<<p> jsFiddle例子/strong>

您的tags_acs_sort函数从不返回任何内容。您还忽略了ab相等的情况。

function sortTags() {
    var options = $('#ddlTags option').sort(tags_asc_sort);
    $("#ddlTags").empty().append(options);
    function tags_asc_sort(a, b) {
        var aText = $(a).text().toUpperCase();
        var bText = $(b).text().toUpperCase();
        if (aText < bText)
            return -1;
        if (aText > bText)
            return 1;
        return 0;
    }
}

一个例子:

var text = 'hello this is test text hello'.split(' ');
function tags_asc_sort(a, b) {
  var aText = a.toUpperCase();
  var bText = b.toUpperCase();
  if (aText < bText)
    return -1;
  if (aText > bText)
    return 1;
  return 0;
}
console.log(text.sort(tags_asc_sort));