如何使Select2 4.0可排序?
我在新版本4.0中遇到了这个问题,并且无法找到任何答案,直到我自己解决了一些工作后的工作。
I had this problem with the new version 4.0, and wasn't able to find any answer, until I myself solved with a work around after some hours of work.
我的解决方案解决方案:
My workaround solution:
首先,使用jquery对其进行排序。
First, make it sortable with jquery.
$("#mySelect").parent().find("ul.select2-selection__rendered").sortable({
containment: 'parent',
update: function() {
orderSortedValues();
}
});
函数orderSortedValues具有以下想法:
更改原始选项的顺序选择输入,并通知select2关于新订单。
The function orderSortedValues has the following idea: Change the order of the options of the original select input, and notifying select2 about the new order.
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);
};
最后,还需要通过下拉列表选择新值来停止自动排序
Finally, it will also be necessary to stop the automatic sorting with selecting a new value through the dropdown
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");
});
}
PS:函数的范围是全局的。你可以改变它......希望能帮助别人。
PS: the scope of the functions are global. You may change it... Hope to help someone else.