在Select2中按名称排序 [英] Sort by name in Select2

查看:66
本文介绍了在Select2中按名称排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以按名称对select2生成的列表进行排序?我有一些代码:

Is there any way to sort my list generated by select2 by name? I have some code :

var dataUser = [{
    "id": "5",
    "text": "BTest"
}, {
    "id": "2",
    "text": "ATest"
}, {
    "id": "8",
    "text": "CTest"
}, {
    "id": "13",
    "text": "DTest"
}];


$("#mylist").select2({
    data: dataUser,
    templateResult: function(data) {
        return data.text;
    },
    sorter: function(data) {    
        return data.sort();
    }
});

http://jsfiddle.net/oe9retsL/4/

此列表按ID排序,但我要按文本排序.

This list sorts by id, but I want sort by text.

推荐答案

您需要为 sort()提供一个函数,该函数包含比较 text 属性的逻辑数组中每个对象的大小.试试这个:

You need to provide a function to sort() which contains the logic to compare the text property of each object in the array. Try this:

sorter: function(data) {
    return data.sort(function(a, b) {
        return a.text < b.text ? -1 : a.text > b.text ? 1 : 0;
    });
}

更新的小提琴

要对选定的选项进行排序,您需要在选择一个选项时在标签上很好地实现类似的逻辑,例如:

To sort the selected options you need to implement similar logic on the tag well when an option is selected, like this:

$("#mylist").select2({
    data: dataUser,
    templateResult: function(data) {
        return data.text;
    },
    sorter: function(data) {
        return data.sort(function(a, b) {
            return a.text < b.text ? -1 : a.text > b.text ? 1 : 0;
        });
    }
}).on("select2:select", function (e) { 
    $('.select2-selection__rendered li.select2-selection__choice').sort(function(a, b) {
        return $(a).text() < $(b).text() ? -1 : $(a).text() > $(b).text() ? 1 : 0;
    }).prependTo('.select2-selection__rendered');
});

更新小提琴

这篇关于在Select2中按名称排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆