我想用jQuery在我的每个选择框周围设置一个红色边框。但它没有成功:
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>
答案 0 :(得分:4)
首先,您的代码不起作用,因为select2-container
元素 兄弟姐妹,所以调用它们上的find()
来让孩子们什么都不返回。只需移除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>