将动态创建的标签移动到select2列表的底部

问题描述

我在select2中使用了创建标签选项。但是,我想将“新类别”选项移到列表的底部而不是第一个。

$(document).ready(function() {
    $('.select2').select2({
        escapeMarkup: function (markup) {
        return markup;
    },templateResult: formatResult,templateSelection: formatResult,tags: true,createTag: function (params) {
        // Don't offset to create a tag if there is no @ symbol
        if (params.term.match(/[a-z]/i)) {
            // Return null to disable tag creation
            return {
                id: params.term,text: params.term +' <span class="new-category-text">[New Category]</span>',tag: true
            }
        }
        return null;
    },matcher: matchCustom,});
});

function matchCustom(params,data) {
    // If there are no search terms,return all of the data
    if ($.trim(params.term) === '') {
        return data;
    }

    // Do not display the item if there is no 'text' property
    if (typeof data.text === 'undefined') {
        return null;
    }

    // `params.term` should be the term that is used for searching
    // `data.text` is the text that is displayed for the data object
    if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) > -1) {
        var modifiedData = $.extend({},data,true);
        // modifiedData.text += ' (matched)';

        // You can return modified objects from here
        // This includes matching the `children` how you want in nested data sets
        return modifiedData;
    }

    // Return `null` if the term should not be displayed
    return null;
}

    function formatResult(state)
    {

        if (state.text === '-- Select --') {
            return '<span class="text-danger">'+state.text+'</span>';
        }
        if (!state.id || !state.element) {
            // console.log(state);
            return state.text;
        }

        if(state.element.dataset.global === '1'){
            // console.log(state);
            return '<span>'+state.text+'</span><span class="float-right">Standard</span>';
        }else{
            return '<span>'+state.text+'</span>';
        }
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>

<div>
  <select class="select2" style="width:200px;" name="cars">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </select>
</div>

而且,这是屏幕截图

enter image description here

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)