如何使Select2 4.0可排序?

Luc*_*ira 1 jquery jquery-select2-4 select2

我在新版本4.0中遇到了这个问题,但直到我自己经过数小时的工作后解决后,才找到任何答案。

Luc*_*ira 5

我的解决方法:

首先,使其与jQuery可排序。

$("#mySelect").parent().find("ul.select2-selection__rendered").sortable({
    containment: 'parent',
    update: function() {
        orderSortedValues();
    }
});
Run Code Online (Sandbox Code Playgroud)

函数orderSortedValues具有以下思想:更改原始选择输入的选项的顺序,并向select2通知新顺序。

orderSortedPassageValues = function() {
    $("#mySelect").parent().find("ul.select2-selection__rendered").children("li[title]").each(function(i, obj){
        var element = $("#mySelect").children("option[value="+obj.title+"]");
        moveElementToEndOfParent(element)
    });
};

moveElementToEndOfParent = function(element) {
    var parent = element.parent();

    element.detach();

    parent.append(element);
};
Run Code Online (Sandbox Code Playgroud)

最后,还需要通过下拉列表选择新值来停止自动排序

stopAutomaticOrdering = function() {    
    $("#mySelect").on("select2:select", function (evt) {
        var id = evt.params.data.id;

        var element = $(this).children("option[value="+id+"]");

        moveElementToEndOfParent(element);

        $(this).trigger("change");
    });
}
Run Code Online (Sandbox Code Playgroud)

PS:功能范围是全局的。您可以更改它...希望能帮助别人。