jQuery 动态 select2 不触发更改事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16062064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamic select2 not firing change event
提问by Phoenix_uy
I have a form with a couple of selects inside. I'm applying the select2 jquery plugin over those selects like this:
我有一个表格,里面有几个选择。我在这些选择上应用 select2 jquery 插件,如下所示:
$("select.company_select, select.positions_select").select2();
The select's work fine, but I have this code to autosubmit my form (I have the autosubmit class on the form tag).
选择的工作正常,但我有这个代码来自动提交我的表单(我在表单标签上有自动提交类)。
var currentData;
$('.autosubmit input, .autosubmit select, .autosubmit textarea').live('focus', function () {
currentData = $(this).val();
});
$('.autosubmit input, .autosubmit select, .autosubmit textarea').live('change', function () {
console.log('autosubmiting...');
var $this = $(this);
if (!currentData || currentData != $this.val()) {
$($this.get(0).form).ajaxSubmit(function (response, status, xhr, $form) {
currentData = "";
});
}
});
The thing is that with the select2, the change or the focus event doesn't fire at all. If I remove the select2, then the events get fired perfectly.
问题是对于 select2,更改或焦点事件根本不会触发。如果我删除 select2,那么事件会被完美触发。
What am I doing wrong?
我究竟做错了什么?
回答by Mikhail Chernykh
Select2 has only 2 events, open
and change
(http://select2.github.io/select2/#events), you are able to add listeners only to them.
You can use open
event instead of focus
for <select>
element.
And please don't use live()
method, as it is deprecated. Use on()
instead.
Select2 只有 2 个事件,open
并且change
(http://select2.github.io/select2/#events),您只能向它们添加侦听器。您可以使用open
event 而不是focus
for <select>
element。并且请不要使用live()
方法,因为它已被弃用。使用on()
来代替。
var currentData;
$(".autosubmit select").on("open", function() {
currentData = $(this).val();
});
$(".autosubmit input").on("focus", function() {
currentData = $(this).val();
});
$(".autosubmit input, .autosubmit select").on("change", function() {
var $this = $(this);
console.log('autosubmitting');
if (!currentData || currentData != $this.val()) {
$($this.get(0).form).ajaxSubmit(function (response, status, xhr, $form) {
currentData = "";
});
}
});
Here is the Fiddle
这是小提琴