繁体   English   中英

jQuery排序功能不起作用

[英]jquery sorting function not working

以下排序功能不适用于我:

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使用类似的功能。 知道可能是什么问题吗?

您需要返回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;
  }
}

jsFiddle示例

您的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)); 

根据先前的答案,并尝试变得更加纯粹,我将尝试使用使用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)); 

暂无
暂无

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

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