延迟选择打开以填充数据

Delaying select2 opening to fill it with data

本文关键字:填充 数据 选择 延迟      更新时间:2023-09-26

我有一个下拉菜单,我通过调用函数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/