如何在我的每个 select2 select 框周围设置边框?

How can I set a border around each of my select2 select box?

我想用 jQuery 在我的每个 select 框周围设置一个红色边框。但是没有成功:

http://jsfiddle.net/jEADR/3795/

<script type="text/javascript" src="//code.jquery.com/jquery-1.8.3.js"></script> 
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.min.js"></script>
 <link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.css">

<select class="select" style="width:300px">
        <option value="AL">Alabama</option>
        <option value="Am">Amalapuram</option>
        <option value="An">Anakapalli</option>
        <option value="Ak">Akkayapalem</option>
        <option value="WY">Wyoming</option>
    </select>
    <select class="select" style="width:300px">
        <option value="AL">Alabama</option>
        <option value="Am">Amalapuram</option>
        <option value="An">Anakapalli</option>
        <option value="Ak">Akkayapalem</option>
        <option value="WY">Wyoming</option>
    </select>

<script>
    $(".select").select2();
    $(".select").each(function() {
    $(this).siblings().find(".select2-container").css({"border-color": "red", "border-weight":"5px", "border-style":"solid"});
    });
</script>

首先,您的代码不起作用,因为 select2-container 元素 兄弟姐妹,因此对它们调用 find() 以获得子元素 returns 没什么。只需删除 find() 调用,并将选择器交给 siblings()。另请注意,您可以缩短 border 规则,如下所示:

$(".select").each(function() {
  $(this).siblings(".select2-container").css('border', '5px solid red');
});

然而,更重要的是,您应该注意,当您可以将规则直接放在 CSS 代码中时,为此使用 JS 代码有点多余:

$(".select").select2();
.select2-container {
  border: 5px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.css">

<select class="select" style="width:300px">
  <option value="AL">Alabama</option>
  <option value="Am">Amalapuram</option>
  <option value="An">Anakapalli</option>
  <option value="Ak">Akkayapalem</option>
  <option value="WY">Wyoming</option>
</select>
<select class="select" style="width:300px">
  <option value="AL">Alabama</option>
  <option value="Am">Amalapuram</option>
  <option value="An">Anakapalli</option>
  <option value="Ak">Akkayapalem</option>
  <option value="WY">Wyoming</option>
</select>

.select2-selection { border: 1px solid gold!important;}