我有以下代码:
$("#dropdowncities").change(function () {
if ($('#dropdowncities option:selected').val()) {
$(".filter-dot").removeClass("hide");
$(".filter-dot").addClass("show");
} else {
$(".filter-dot").removeClass('show');
$(".filter-dot").addClass("hide");
}
});
.filter-dot {
width:10px;
height:10px;
background:red;
border-radius:50%;
}
.show {display:block;}
.hide {display:none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="filter-dot hide"></div>
<select id="dropdowncities">
<option>Select</option>
<option>This is an option</option>
<option>This is another Option</option>
<option>This is another Option</option>
<option>This is another Option</option>
<option>This is another Option</option>
<option>This is another Option</option>
<option>This is another Option</option>
<option>This is another Option</option>
<option>This is another Option</option>
<option>This is another Option</option>
</select>
我想这样做,如果选择框有任何选项,则必须显示“filter-dot”元素,而当选择框没有选择任何选项时,则必须隐藏“filter-dot”元素。
最佳答案
您正在检查该值是否为假值,您真的想检查当前值是否不是默认值。您可以通过将当前值与文本“选择”进行比较来做到这一点:
$("#dropdowncities").change(function () {
switch($('#dropdowncities option:selected').val()) {
case "Select":
$(".filter-dot").removeClass('show');
$(".filter-dot").addClass("hide");
break;
default:
$(".filter-dot").removeClass("hide");
$(".filter-dot").addClass("show");
}
});
.filter-dot {
width:10px;
height:10px;
background:red;
border-radius:50%;
}
.show {display:block;}
.hide {display:none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="filter-dot hide"></div>
<select id="dropdowncities">
<option>Select</option>
<option>This is an option</option>
<option>This is another Option</option>
<option>This is another Option</option>
<option>This is another Option</option>
<option>This is another Option</option>
<option>This is another Option</option>
<option>This is another Option</option>
<option>This is another Option</option>
<option>This is another Option</option>
<option>This is another Option</option>
</select>
关于jquery - 当选择框选项被选中时做一些事情,否则使用 jquery 做其他事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59058903/