简体   繁体   中英

jquery Select2: How to add attributes to li element in DropDown

I use the select2 plugin from jquery and get my data over an ajax load. When I set the response I want to add attributes to the li -elements of my dropdown. I already tried it with calling a function in " templateResult " but there I can only give back the vakue which is IN the <li></li> tags

My javascript:

var autocomplete = function () {
        $("body").find("#myDropDown").select2({
            language: "es",
            ajax: {
                url: searchDataUrl,
                type: "POST",
                // dataType: 'json',
                delay: 250,
                data: function (params) {
                    return {
                        term: params.term, // search term
                        page: params.page
                    };
                },
                processResults: function (data, params) {
                    return {
                        results: data.userData,
                        pagination: {
                            more: (params.page * 30) < data.total_count
                        }
                    };
                },
                cache: true
            },
            createTag: function (params) {
                var term = $.trim(params.term);

                if (term === '') {
                    return null;
                }

                return {
                    id: term,
                    text: term,
                    newTag: true // add additional parameters
                }
            },
            escapeMarkup: function (markup) { return markup; },
            minimumInputLength: 3,
            templateResult: formatReponse, //With this it doesnt work
        });
    };

And the function from my templateResult Call:

//When I do this, I have a "<li>"-Tag within a "<li>"-Tag

var formatReponse = function (data) {

        return '<li data-id="'+data.id+'" class="select2-results__option" role="treeitem">'+data.text+'</li>';

      };

Can anybody help me with this? THANKS!

use the .attr(att,val) function like this:

Give your <li> an id name like liID in <li id='liID'> the following example then give the name of the attribute you want to change in the example given as attributeToChange then give the value you want to set in the atribute in the example: valueToSet. good luck

$('#liID').attr('attributeToChange', 'valueToSet');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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