13

Select2 は、この問題<select>で説明されているように、タグで初期化されたときに無効なオプションをサポートします

ただし、リモート データで同じ結果を得る方法が見つかりません。カスタム フォーマット関数を使用する必要がありますか? ユーザーがそれを選択できないようにするにはどうすればよいですか? それとも、これはどこかに組み込まれていますか?

ありがとう!

4

2 に答える 2

31

disabled: trueSelect2 3.4.2 では、特定の結果オブジェクトにプロパティを追加するだけです。関数を使用した実際の例query:

$('input').select2({
    query: function(query) {
        //do ajax call which retrieves the results array in this format:
        var data = {results: [
            { id: 1, text: 'disabled option', disabled: true },
            { id: 1, text: 'hi' }
        ]};
        //pass it to the query callback inside your Ajax callback:
        query.callback(data);
    }
});

デモ


ajax関数と同じ形式で結果オブジェクト配列を受け入れるラッパーを使用して、同じことを行うことができますquery

(jsFiddle の JSON API を介して) 実際の Ajax 呼び出しを使用したデモを次に示します。

$('input').select2({
    ajax: {
        url: '/echo/json/',
        dataType: 'json',
        params: {
            method: 'post'
        },
        data: function (term, page) {
            // Data to be sent to the server. Usually it is just the "term"
            // parameter (and page if using pagination).
            // However, since this API simply echoes back what we send,
            // I'll build the results array here
            var resultsArr = [];
            for (var i = 0; i < 10; i++) {
                resultsArr.push({
                    id: i,
                    text: 'opt'+i,
                    //randomly disable a couple options for demo purposes
                    disabled: Math.random() < .3
                });
            }
            return {
                json: JSON.stringify(resultsArr)
            }
        },
        results: function(data, page) {
            //data param === received response from the server. As dataType
            //is json, jQuery automatically parses the response into an object.
            //So, in this case, we received the resultsArr that we sent.
            //Now return it in the correct format: { results: resultsArr }
            return { results: data };
        }
    }
});

デモ

この最後の例のdata関数は、jsFiddle API を適切に使用するためのものであることを思い出してくださいdata。クエリ用語を送信する元の関数を保持する必要があります。disabled: true最初の例と同じ形式で、無効にするプロパティが結果オブジェクトに含まれるように応答を変更するだけです。

于 2013-08-18T01:25:27.177 に答える