如何防止从select2中删除标签

我创建了一个带tags:true的select2小部件tags:true 。 有没有办法通过单击下拉列表中的选定项目来阻止删除标记,以便只能通过单击标记中的十字来删除标记?

您可以使用事件select2:unselecting取消项目中的标签删除,例如

 $(".js-example-tags").select2({ tags: true }).on("select2:unselecting", function (e) { // check if originalEvent.currentTarget.className is "select2-results__option" (in other words if it was raised by a item in the dropdown) if ($(e.params.args.originalEvent.currentTarget).hasClass("select2-results__option")){ e.preventDefault(); // close the dropdown $(".js-example-tags").select2().trigger("close"); } }); 

JSFiddle演示

我发现存在一个locked的选项调用,我可以这样做。

只需在选项中添加选项locked="locked" ,如下所示:

  

准备好了。 如果需要,您可以添加在选择中开始选择的选项,如下所示:

  

例如

 $(function() { $('.select2').select2({ tags: true, placeholder: 'Select an option', templateSelection : function (tag, container){ // here we are finding option element of tag and // if it has property 'locked' we will add class 'locked-tag' // to be able to style element in select var $option = $('.select2 option[value="'+tag.id+'"]'); if ($option.attr('locked')){ $(container).addClass('locked-tag'); tag.locked = true; } return tag.text; }, }) .on('select2:unselecting', function(e){ // before removing tag we check option element of tag and // if it has property 'locked' we will create error to prevent all select2 functionality if ($(e.params.args.data.element).attr('locked')) { e.select2.pleaseStop(); } }); }); 
 /* remove X from locked tag */ .locked-tag .select2-selection__choice__remove{ display: none!important; } /* I suggest to hide all selected tags from drop down list */ .select2-results__option[aria-selected="true"]{ display: none; } .select2{ width: 100% !important; }