jQuery 隐藏/显示 Select2

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

Hide/Show Select2

jqueryhideshowselect2

提问by Marquinho Peli

I want to hide or show my select2, but I can't find a method in the API. I'm using a workaround, hiding the parent, like this:

我想隐藏或显示我的 select2,但在 API 中找不到方法。我正在使用一种解决方法,隐藏父级,如下所示:

$(document).on('change', '.country', function () {
    if ($(this).val() == $(this).data('current-countryCode')) {
        $('#states').parent().show();
    }
    else {
        $('#states').parent().hide();
    }
});

But I'd like to know if anyone could help or if even exists such a method in the API.

但我想知道是否有人可以提供帮助,或者 API 中是否存在这样的方法。

回答by Bindrid

I do a similar thing, however I hide the select2 container which is always the next node over from the start point so it would look like.

我做了类似的事情,但是我隐藏了 select2 容器,它总是从起点开始的下一个节点,所以它看起来像。

$(document).on('change', '.country', function () {
    if ($(this).val() == $(this).data('current-countryCode')) {
        $('#states').next(".select2-container").show();
    }
    else {
        $('#states').next(".select2-container").hide();
    }
});

So I have been taking the same approach you have

所以我一直在采取与你相同的方法

回答by Zein

This worked for me..

这对我有用..

jQuery("#my-select2").select2().next().hide();

回答by Pila 77

The problem is that you have to hide all the items associated with the select2 dropdown (all that the plugin generates to do the magic).

问题是您必须隐藏与 select2 下拉列表关联的所有项目(插件生成的所有项目以发挥作用)。

I solved using a div that contains the select2 dropdown and show/hide this div.

我使用包含 select2 下拉列表并显示/隐藏此 div 的 div 解决了这个问题。

回答by dMedia

One more workaround – you can add a class to select2 object at creation

另一种解决方法 - 您可以在创建时向 select2 对象添加一个类

$("#user-box").select2({
    containerCssClass : "show-hide"
});

...and then hide it when you want with

...然后在需要时隐藏它

$(".show-hide").parent().parent().hide();

回答by Mircea Voivod

Easier by extending $.fn

通过扩展 $.fn 更容易

    $.fn.toggleSelect2 = function(state) {
        return this.each(function() {
            $.fn[state ? 'show' : 'hide'].apply($(this).next('.select2-container'));
        });
    };

Then simply call it on the select element.

然后只需在 select 元素上调用它。

$('select').toggleSelect2(true); //Show

or

或者

$('select').toggleSelect2(false); //hide