jQuery 将类添加到 select2 元素

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

Add class to select2 element

jqueryjquery-select2

提问by Deac Karns

The documentation is either terrible or I'm missing something. I'm trying to add an error class to a select2 box for form validation. It's just a 1px red border.

文档要么很糟糕,要么我遗漏了一些东西。我正在尝试将错误类添加到 select2 框以进行表单验证。它只是一个 1px 的红色边框。

I found the containerCssClassmethod in the documentation, but I'm not sure how to apply it.

containerCssClass在文档中找到了该方法,但我不确定如何应用它。

I have tried the following with no luck:

我尝试了以下但没有运气:

$("#myBox").select2().containerCssClass('error');

回答by Niels

jQuery uses JSON objects to initialize, so I guess this one will as well:\

jQuery 使用 JSON 对象来初始化,所以我猜这个也是:\

$("#myBox").select2({ containerCssClass : "error" });

If you want to add/remove a class you can do this after you initialized it

如果您想添加/删除一个类,您可以在初始化它后执行此操作

$($("#myBox").select2("container")).addClass("error");
$($("#myBox").select2("container")).removeClass("error");

The above function gets the DOM node of the main container of select2 e.g.: $("#myBox").select2("container")

上述函数获取select2的主容器的DOM节点eg: $("#myBox").select2("container")

Important
You will need to use the container method to get the container since you won't edit the SELECT directly but select2 will generate other HTML to simulate a SELECT which is stylable.

重要
您将需要使用容器方法来获取容器,因为您不会直接编辑 SELECT 但 select2 将生成其他 HTML 来模拟可样式化的 SELECT。

回答by Jared

For already initialized select2 element I have tried @Niels solution but it resulted in an error: Uncaught TypeError: Cannot read property 'apply' of undefined

对于已经初始化的 select2 元素,我尝试了 @Niels 解决方案,但导致错误: Uncaught TypeError: Cannot read property 'apply' of undefined

Went into the source and this has been working instead:

进入源代码,这一直在起作用:

$($('#myBox').data('select2').$container).addClass('error')
$($('#myBox').data('select2').$container).removeClass('error')

Using select2 v4.0.3 full

使用 select2 v4.0.3 完整版

回答by Samsquanch

According to the documentation, containerCssClassis only a constructor property. The best you're probably going to be able to do is reinitialize it when you get an error via:

根据文档,containerCssClass只是一个构造函数属性。当您通过以下方式收到错误时,您可能能够做的最好的事情是重新初始化它:

$("#myBox").select2({
    containerCssClass: "error" 
});

Note from comments: If you get Uncaught Error: No select2/compat/containerCss(…), you need to include the select2.full.js version instead of the basic one

评论中的注意事项:如果您收到 Uncaught Error: No select2/compat/containerCss(...),您需要包含 select2.full.js 版本而不是基本版本

回答by Shahin Dohan

For those wandering here from google, the property containerCssClasshas a misleading name since it doesn't actually add any classes to the container element, but rather to the selection element. You can see this when you inspect the generated html.

对于那些从 google 徘徊在这里的人来说,该属性containerCssClass的名称具有误导性,因为它实际上并未向容器元素添加任何类,而是向选择元素添加任何类。当您检查生成的 html 时,您可以看到这一点。

I came across a nice little hack herethat allows you to apply your css class to the container by adding it to the themeproperty, like so:

我在这里遇到了一个不错的小技巧它允许您通过将 css 类添加到theme属性来将其应用于容器,如下所示:

$('#my-select').select2({
    theme: "bootstrap myCssClass",
});

回答by steve joe

use theme option.

使用主题选项。

 $(".select").select2({
        placeholder: "",
        allowClear: false,
        theme: "custom-option-select"
    });

回答by trisztan

Easiest way:

最简单的方法:

Create a parent class like

创建一个父类,如

<div class="select-error">
    <select id="select2" name="select2" data-required class="form-control">
        <option value="" selected>No selected</option>
        <option value="1">First</option>
        <option value="2">Second</option>
    </select>
</div>

when you validate it with jquery or php just add style or css to .select-error class like

当您使用 jquery 或 php 验证它时,只需将样式或 css 添加到 .select-error 类中

style="border:1px solid red; border-radius: 4px"

jQuery example:

jQuery 示例:

$('[data-required]').each(function() {
  if (!$(this).val()) {
    if ($(this).data('select2')) {
      $('.select-error').css({
        'border': '1px solid red',
        'border-radius': '4px'
      });
    }
  });

回答by ycscholes

You can use dropdownCssClass opiton

您可以使用 dropdownCssClass 选项

$("#myBox").select2({
    containerCssClass: "error" 
});