【问题标题】:Select2 reinitialize not workingSelect2重新初始化不起作用
【发布时间】:2017-06-29 01:20:27
【问题描述】:

我有一个选择框,它依赖于另一个选择框。我正在使用 AJAX 更改第二个(依赖)选择框上的选项。另外,我在两个选择框上都使用了 select2 插件,例如:

$(document).ready(function() {
    $('#mySelect2').select2({
        // options
        }
    });
});

我的问题是,在刷新第二个选择框后,select2 就从这个选择框中消失了,并像普通的选择框一样向我显示。在这里的某个地方,我看到我可以使用销毁并“重新初始化”选择。但是在我使用的 mySelect1.onChange 事件中:

$('#mySelect2').select2("destroy");
$('#mySelect2').select2({
        // same options
});

看起来选择框被破坏但没有再次初始化。因为再次刷新后,我的控制台说:

The select2('destroy') method was called on an element that is not using Select2.

感谢您的任何回答,我是新手。

【问题讨论】:

  • 您的两个选择框是否包含相同的 ID? #mySelect2。显示一些 html
  • 不,它们是不同的<select name="subjects[]" class="form-control input-sm select2 select2-hidden-accessible" id="frm-searchLecturesForm-form-subjects" multiple="" tabindex="-1" aria-hidden="true"> ... options ... </select><select name="topics[]" class="form-control input-sm select2 select2-hidden-accessible" id="frm-searchLecturesForm-form-topics" multiple="" tabindex="-1" aria-hidden="true"> ... options ... </select>
  • 我对它们都应用了 select2 并且两者都有效...直到我在第一次选择中更改所选选项并在第二次选择中刷新数据“#frm-searchLecturesForm-form-topics”
  • 给我看一些真实的代码,而不是一个例子

标签: javascript jquery drop-down-menu select2


【解决方案1】:

尽量不要破坏 select2 元素,加载新的 data link 然后 .trigger('change') link。例如:

// new data arrived...
var new_data = [...]

$('#mySelect2').select2({
    // update data
    data: new_data
});
$('#mySelect2').trigger("change");

【讨论】:

  • 它不适用于我的代码..我的 new_data 来自 Ajax Success..但它应用到当前选择框,所以我对旧 SelectBox 数据及其附加新数据也有问题。 . 任何解决方案,所以它只会显示 ajax 返回数据?
  • $.post('/get_ajax_data/',{custom_param:1}, function(data){ var result = data.result; $("#client1_select").select2({ data:result }); $('#client1_select').trigger("change"); });
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-10
  • 1970-01-01
  • 2012-02-26
  • 2014-03-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多