解决select2拖动排序后修改时丢失排序结果

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);
    }
});

问题解决

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值