选择 select2 后触发一个动作 [英] Trigger an action after selection select2
问题描述
我正在使用 select2 库 进行搜索.
有没有办法在选择搜索结果后触发操作?例如打开一个弹出窗口,或一个简单的 js 警报.
I am using select2 library for my search.
is there any way to trigger an action after selecting a search result? e.g. open a popup, or a simple js alert.
$("#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
});
推荐答案
请参阅文档事件部分
根据版本的不同,下面的代码片段之一应该可以为您提供所需的事件,或者只需将select2-selecting"替换为change".
Depending on the version, one of the snippets below should give you the event you want, alternatively just replace "select2-selecting" with "change".
版本 4.0 +
事件现在的格式为:select2:selecting
(而不是select2-selecting
)
Events are now in format: select2:selecting
(instead of select2-selecting
)
感谢snakey通知4.0已经改变了
Thanks to snakey for the notification that this has changed as of 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
的文档如下:
Just to clarify, the documentation for select2-selecting
reads:
select2-选择当一个选项被选中时触发下拉菜单,但在对选择进行任何修改之前.该事件用于允许用户通过调用拒绝选择event.preventDefault()
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
可能更适合您的需求,具体取决于您是希望完成选择然后执行您的活动,还是可能阻止更改.
So change
may be more appropriate for your needs, depending on whether you want the selection to complete and then do your event, or potentially block the change.
这篇关于选择 select2 后触发一个动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!