延迟选择打开以填充数据
Delaying select2 opening to fill it with data
我有一个下拉菜单,我通过调用函数list()
来填充数据,这使得json调用并根据不同的参数过滤必要的数据(这是非常复杂的,我不使用内置的ajax功能)。
下面是我的代码:
$("select.mission:visible").on("select2-opening", function() { list(); });
它完美地工作,除了一个小问题-更新列表是在打开时完成的,所以当你第一次打开下拉菜单时,更新的列表不会显示。第二次打开显示正确的选项。
我考虑使用select2-focus
,但它被调用两次,在开始和结束。第二次调用重新填充列表,而选中的选项仍然突出显示,值传递为undefined
。
我寻找的解决方案是延迟列表的打开,让它填充。有什么想法吗?
现在提这个问题有点晚了。我遇到了和你类似的问题,我的解决方法如下:
$("select.mission:visible").on("select2-open", function() {
$.getJSON("path-to-json", function(data) {
var results_data = [];
$.each(data.feed.entry, function(i, entry) {
results_data.push({'id':entry.id, 'text':entry.text})
});
// if your element select.mission:visible is select convert it to input:hidden
var id = $(this).attr('id') // get old id
var name = $(this).attr('name') // get old name
var oldVal = $(this).val() // get old value
$('select.missions').empty(); // empty select options
$(this).select2('distroy') // destroy current select2 obj
$(this).replaceWith(`<input type='hidden' class='mission' id='${id}' name='${name}'>`) // convert select element to input element
$(this).val(oldVal) // set new input element to previous value
$(this).select2({data:results_data}) // set new option items to new input element select2
$(this).select2('open') // force select2 element to open dropdown
});
});
因为我不知道你使用的是哪个版本的select2,但从你的代码,我假设你正在使用select2版本3.x。欲了解更多详细信息,请访问https://select2.github.io/select2/
相关文章:
- 如何在Highchart中动态填充数据
- 使用jquery在选择框中的选项中填充数据
- 使用jquery、javascript重新填充数据
- 如何从 API 填充数据并加载到下拉列表中
- 通过遍历JSON文件来填充数据列表选项
- 在引导模式中,点击相应的datatables行中的按钮,填充数据
- 当选择District时,PHP将从数据库中填充数据
- 从角度工厂返回数据,返回对象后填充数据
- 高图表 - 从数组填充数据
- 在承诺函数从 pouchdb 填充数据之前触发 Ionic/Angular $watch的问题
- 无法用同位素填充数据
- 使用 php 发送 json 填充数据表
- JQuery - 在表单中填充数据的正确方法
- 翡翠选择字段填充数据
- C# MVC 填充数据表中的下拉列表组
- 自动填充数据被javascript的onchange事件覆盖
- 如何在html中只使用ng repeat来填充数据,而不使用repeat html's元素
- 用Firebase和Angular填充数据表
- 通过JS Ajax调用问题填充数据
- 使用两个ajax调用在两个html表中填充数据