简体   繁体   English

以编程方式删除select2中添加的新标签

[英]remove added new tag in select2 programmatically

I've been using select2 for a custom component and wonder whether there is a method to remove a tag created by a user programmatically. 我一直在将select2用于自定义组件,并且想知道是否存在一种方法来删除用户以编程方式创建的标记。 I've tried the following way by getting the data array in select2 and then removing the necessary element and then updating the select2 data attribute. 我尝试了以下方法,将数据数组放入select2中,然后删除必需的元素,然后更新select2数据属性。

var select2Data = $('.members').select2('data'); //original select2 element data
var select2NewUser = $('.new-tag').data(); //data related to the new tag

$.each(select2Data,function(i){
    if(select2Data[i].id === select2NewUser.id){
        select2Data.splice(i,1);
        return false;
        }
})

$('.members').select2('data',select2Data); //updates the modified data tag

$('.new-tag').remove();

This method only update the data object! 此方法仅更新数据对象! The view is not updated and the element is still in the select2. 视图不会更新,并且元素仍在select2中。 How can I remove a tag in select2? 如何在select2中删除标签?

It looks like select2 is not having an option to refresh the list. 似乎select2没有选择刷新列表的选项。 You can try destroying the select and recreate with updated values. 您可以尝试销毁选择并使用更新的值重新创建。 Try 尝试

$('.members').select2("destroy");

and reinitialize with 然后用重新初始化

$('.members').select2({data: UpdatedData });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM