jquery - 选择 select2 后触发一个 Action

标签 jquery search jquery-select2

我正在使用 select2 library供我搜索。
选择搜索结果后有什么方法可以触发操作吗?例如打开一个弹出窗口,或一个简单的 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
});

最佳答案

参见 documentation events section

根据版本的不同,下面的片段之一应该会为您提供所需的事件,或者只需将“select2-selecting”替换为“change”。

版本 4.0 +

事件现在的格式是:select2:selecting(而不是 select2-selecting)

感谢 snakey 通知从 4.0 开始这已经改变

$('#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 Fired when a choice is being selected in the dropdown, but before any modification has been made to the selection. This event is used to allow the user to reject selection by calling event.preventDefault()

而变化有:

change Fired when selection is changed.

因此 change 可能更适合您的需求,具体取决于您是希望选择完成然后执行您的事件,还是可能阻止更改。

关于jquery - 选择 select2 后触发一个 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18615108/

相关文章:

javascript - 如何使用其他元素解析 div 内的文本?

javascript - "Paste"使用 jQuery 的文本字段按钮

Android,重新定义搜索按钮

javascript - 如何将按钮放入 select2 结果项并处理其点击?

javascript - 对新 DOM 元素使用相同的函数

javascript - 使用 jQuery 将某个类的每个 div 从其父级的开头移动到结尾

elasticsearch - 结合使用filter和function_score- Elasticsearch 不会计算得分?

algorithm - 经典(基于递归)深度优先搜索是否比基于堆栈的 DFS 的内存效率更高?

javascript - Select2 下拉更改事件不起作用

jquery - 在 Rails 中使用 select2 gem