javascript 加载数据后从 Select2 中获取项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32335642/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:07:52  来源:igfitidea点击:

Get items from Select2 after data has been loaded

javascriptjqueryjquery-select2

提问by Maximus Decimus

I'm trying to force the open method and select item with select2 like this.

我正在尝试强制打开方法并像这样使用 select2 选择项目。

    $(".select").select2('open')
    $(".select").on('select2-loaded', function (e) {
        items = e.items.results;
        if (items.length == 1) {
            $(this).val(items[0].text);
        }
    });
    $(".select").select2('close');

But I cannot get inside the select2-loaded evaluation and the close is happening also to quick. I want to select the first element by default if there is only one element on the list.

但是我无法进入 select2-loaded 评估,并且关闭也很快。如果列表中只有一个元素,我想默认选择第一个元素。

When the 'open' occurs, it automatically performs the mechanism to get and load all the elements in my list. If I comment the close method it will take some milliseconds to display the elements on the list.

当“打开”发生时,它会自动执行获取和加载列表中所有元素的机制。如果我评论 close 方法,则需要几毫秒才能显示列表中的元素。

But what I want is to refresh my list (this is done by the open) then I want to select only if there one element and the close my list ('select')

但是我想要的是刷新我的列表(这是由打开完成的)然后我只想选择只有一个元素并关闭我的列表(“选择”)

How can I achieve this? This behaviour will be trigger by a onchange event of another list. (nested selects)

我怎样才能做到这一点?此行为将由另一个列表的 onchange 事件触发。(嵌套选择)

回答by uri2x

You should move the closecall INSIDE the select2-loadedevent, so it'll only close the select element after it selected the item. Otherwise you're opening, setting event for future event, then closing immediately.

您应该将close调用移到select2-loaded事件内部,这样它只会在选择项目后关闭 select 元素。否则,您正在打开,为将来的事件设置事件,然后立即关闭。

$(".select").select2('open')
$(".select").on('select2-loaded', function (e) {
    items = e.items.results;
    if (items.length == 1) {
        $(this).val(items[0].text);
        $(".select").select2('close');
    }
});