jquery - 当一个选择框选项被选中时做某事,否则使用 jquery 做其他事情
问题描述
我有以下代码:
$("#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>
I want to make it so if select box has any option, then the "filter-dot" element must be displayed and when select box has no option selected then the "filter-dot" element must be hidden.
解决方案
您正在检查该值是否为假,您真的想检查当前值是否不是默认值。您可以通过将当前值与文本“选择”进行比较来做到这一点:
$("#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>
推荐阅读
- wso2 - WSO2 身份服务器模式集群
- node.js - 从 S3 检索大量数据时,如何绕过 Heroku 的超时?
- sql - 计算用零替换缺失行的预定义值的平均值和标准偏差
- python-3.x - UnicodeDecodeError:“charmap”编解码器无法解码位置 20318 中的字节 0x9d:字符映射到
- python - 如何启动 __name__ == '__main__': 使用来自另一个 .py 文件的特定输入?
- java - 使用实体的复合键作为另一个实体中的 ManyToMany 键
- git - 为什么`git diff-tree
` 应用于第一次提交时不打印结果? - kubernetes-ingress - 使用 Kong-Ingress-Controller 部署 Kong 时如何访问 Kong 管理 API
- php - 表单页面未重定向到 Laravel 中的所需页面
- java - 扫描“打电话回家”的依赖罐?