本文介绍了如何为Select2的预选值设置模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我预选Select2的值,如下所示。

function formatState(state) {

    console.log(state.text2) // I found undefined here.

    console.log('hello') // This is called when values are populating.

    if (!state.id) { return state.text; }
    var output = $('<span class="tooltip" title="' + state.text2 + '">' + state.text + '</span>');   // I would like to template here. 
    return output;
};

function resultfucntion(state) {
    if (!state.id) { return state.text;}
    var $state = $('<span>' + state.text + '('+ state.text1 +')</span>');
    return $state;
};

// Initialise select2
let selectEle = cellEle.children("select").select2({        
    ajax: {
        // more code here
        processResults: function (data) {                
            var options = [];
            if (data) {
                $.each(data, function (index, text) {
                    var user_data = '<table> 
                        <tr> 
                        <td>Organisation</td> 
                        <td>'+text[2][1]+'</td> 
                        </tr> 
                        <tr> 
                        <td>Age</td> 
                        <td>'+ text[2][0]+'</td> 
                        </tr> 
                    </table>';          
                    options.push({ id: index, text: text[0], text1: text[1], text2: user_data });
                });
            }
            return {
                results: options,
                more: false
            };
        },
    },
    templateSelection: formatState,
    templateResult: resultfucntion,
});        

// Above code is working fine

// I am trying to fetch preselected values here

$.ajax({
// more code here
}).then(function (data) {
    if (data) {
        $.each(data, function (index,text) {
            var user_data = '<table> 
                <tr> 
                <td>Organisation</td> 
                <td>'+text[0][1]+'</td> 
                </tr> 
                <tr> 
                <td>Age</td> 
                <td>'+ text[0][0]+'</td> 
                </tr> 
            </table>';

            var opt = new Option(text["text"], text["id"], true, true);
            opt.attr("title", user_data);  // I am trying to add Title here
            selectEle.append(opt); 
        });
    }                
    selectEle.trigger("change");
});

我发现在填充预选值时会调用formatState函数。但我将undefined作为state.text2的值。

如何获取state.text2的值以用作预选值的title

推荐答案

可能模板在AJAX请求之前执行,请添加条件

if(typeof state.text2 !== 'undefined) { return false; }  

If(!state.id){Return state.Text;}之前和控制台在条件之后

并在AJAX请求之后检查是否收到该文本

这篇关于如何为Select2的预选值设置模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 03:16