给select2中选中的列表项添加属性

Add attributes to the selected list items in select2

Here is a working jsfiddle. I wish to add attributes (in particular id) to the <li> elements created. My use case is slightly different from the fiddle, rather than using an array, I am getting my data from ajax. In addition I want to give my users flexibility to create new tags if the same are not present in database. To save newly created item list having id's is a much better handle than just plain classes. Can I modify the attributes of the <li> 个元素已创建?

我的实际代码是这样的:

$(".js-data-example-ajax").select2({
        ajax : {
            url : "/content/search_skills",
            dataType : 'json',
            delay : 250,
            data : function(params) {
                return {
                    q : params.term, // search term
                    page : params.page
                };
            },
            processResults : function(data, params) {
                params.page = params.page || 1;

                return {
                    results : data.items,
                    pagination : {
                        more : (params.page * 5) < data.total_count
                    }
                };
            },
            cache : true
        },
        escapeMarkup : function(markup) {
            return markup;
        }, // let our custom formatter work
        minimumInputLength : 1,
        templateResult : formatRepo,
        templateSelection : formatRepoSelection,
        tags : true,
        createTag : function (params) {
            return {
                id: params.term,
                text: params.term,
                newOption: true
              }
            },
    });
    function formatRepo(repo) {
        if (repo.loading)
            return repo.text;

        var markup = '<ul class="list-group clear-list m-t">' + '<li class="list-group-item fist-item"><span class="pull-right">' + repo.id + '</span> <span class="label label-success">' + repo.count + '</span> ' + repo.text + '</li>';

        return markup;
    }

     function formatRepoSelection (repo) {
         var markup = repo.text;
         return markup;
          }

而我的 jsp (html) 是:

<select class="js-data-example-ajax" style="width: 100%" multiple="multiple">
    //Iterating through database query result to pre-load option items
    <option value="<%=skill_objective.get("id")%>" selected="selected"><%=skill_objective.get("id")%> <%=skill_objective.get("name") %></option>
</select>

Here 是一个可行的解决方案:

$(".js-data-example-ajax").select2('data') 会给我所有选中对象的散列值。