如何在 select2 中添加新标签?

How to add new tags in select2?

我正在尝试从我的 api 中获取标签。一切正常,但我无法添加新标签。这是我尝试过的:

$(function(){
        var user_email = localStorage.getItem('email');
        var api = localStorage.getItem("user_api_key");
        var auth = "apikey" +' ' +(user_email+":"+api);
        $('#s2id_id_add-places').select2({
            multiple: true,
            tags: [],
            tokenSeparators: [",", " "],
            width: "200px",
            ajax: {
                placeholder: "Click to enter who",
                type: "GET",
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("Authorization", auth);
                    xhr.setRequestHeader("Content-Type","application/json");
                    xhr.setRequestHeader("Accept","application/json");
                },
                url: "https://example.com/api/v3/places/",
                dataType: "json",
                contentType: "application/json",
                processData: true,
                quietMillis: 50,
                data: function(term) {
                    return {
                        term: term
                    };
                },
                results: function(data) {
                    var results = [];
                    if(data.objects.length > 0) {
                        for (i=0; i<data.objects.length; i++) {
                            results.push({id: data.objects[i].id, text: data.objects[i].label, isNew: true});
                        }
                    }
                    return {
                        results: results
                    };
                },
    });
    });

通过使用上面的代码,我只能获取标签,但无法添加新标签。如何添加新标签?

请帮忙

$("#e11_2").select2({
  createSearchChoice: function(term, data) { 

      if ($(data).filter( function() { 
           return this.text.localeCompare(term)===0;   
      }).length===0) {
           return {id:term, text:term};
      } 
  },
  multiple: true,
  data: [{id: 0, text: 'story'},{id: 1, text: 'bug'},{id: 2, text: 'task'}]
});

您必须创建一个像 createSearchChoice 这样的函数,return 是一个具有 'id' 和 'text' 的对象。在其他情况下,如果您 return 未定义,则不会创建该选项。