82

検索にselect2ライブラリを使用しています。
検索結果を選択した後にアクションをトリガーする方法はありますか? たとえば、ポップアップを開くか、単純な js アラートを開きます。

$("#e6").select2({
    placeholder: "Enter an item id please",
    minimumInputLength: 1,
    ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
        url: "index.php?r=sia/searchresults",
        dataType: 'jsonp',
        quietMillis: 3000,
        data: function (term, page) {
        return {
            q: term, // search term
            page_limit: 10,
            id: 10
            };
        },
        results: function (data, page) { // parse the results into the format expected by Select2.
            // since we are using custom formatting functions we do not need to alter remote JSON data
            return {results: data};
        },
    },

    formatResult: movieFormatResult, // omitted for brevity, see the source of this page
    formatSelection: movieFormatSelection, // omitted for brevity, see the source of this page
    dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
    escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
});
4

7 に答える 7

173

ドキュメンテーション イベント セクションを参照してください。

バージョンによっては、以下のスニペットのいずれかで必要なイベントが得られるはずです。代わりに、「select2-selecting」を「change」に置き換えるだけです。

バージョン 4.0 +

イベントの形式が次のようになりました: select2:selecting(の代わりにselect2-selecting)

これが4.0の時点で変更されたことを通知してくれたsnakeyに感謝します

$('#yourselect').on("select2:selecting", function(e) { 
   // what you would like to happen
});

バージョン 4.0 より前

$('#yourselect').on("select2-selecting", function(e) { 
   // what you would like to happen
});

明確にするために、ドキュメントのselect2-selecting読み取り:

select2-selecting ドロップダウンで選択肢が選択されているときに、選択内容が変更される前に発生します。このイベントは、ユーザーが event.preventDefault() を呼び出して選択を拒否できるようにするために使用されます。

一方、変更には次のものがあります。

change 選択が変更されたときに発生します。

選択changeを完了してからイベントを実行するか、変更をブロックする可能性があるかによって、ニーズにより適している場合があります。

于 2013-09-04T13:30:54.503 に答える
27

select2 イベント名にいくつかの変更が加えられたので (v. 4 以降だと思います)、'-'がこの':'に変更されました。
次の例を参照してください。

$('#select').on("select2:select", function(e) { 
    //Do stuff
});

「select2」プラグイン サイトですべてのイベントを確認できます: select2 Events

于 2016-04-10T19:17:26.533 に答える