select2是个常用的选择控件。现在业务需要对里面选项排序。
网上例子添加jquery-ui、sortable.js与如下代码为止,可以支持拖拽排序
$("ul.select2-selection__rendered").sortable({
containment: 'parent'
});
现实中测试发现问题,如果拖拽标签后,再添加新标签或删除既存标签,之前拖拽效果会失效,排序会回到最开始,经确认,默认排序是根据上面隐藏的select2的option决定的。因此添加根据标签排序时调整option,以修改默认排序。
$("ul.select2-selection__rendered").sortable({
containment: 'parent',
update: function() {
$select = $(this).closest(".select2-container").prev();
var options = $select.find("option");
var newoptions = [];
// 清空option
$(this).find(".select2-selection__choice").each(function (i, tag) {
options.each(function (j, option) {
if($(tag).attr("title") == $(option).text()){
newoptions.push(option);
}
});
});
$select.empty();
$select.append(newoptions);
}
});
问题解决