jquery - 当选择框选项被选中时做一些事情,否则使用 jquery 做其他事情

标签 jquery html css

我有以下代码:

$("#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/

相关文章:

javascript - 如何使用 Y.StyleSheet 设计样式

css - 删除未使用的 js/css 引用

javascript - 为什么我的下拉菜单在导航栏上不起作用?

jquery - 与 CSS 作斗争的艰难时期。无法获得背景图像下方的背景颜色

jquery - 如果元素已存在,则使函数返回 false

javascript - 在激活验证之前查找 jQuery Accordion 中的元素

html - 表标签创建与只读网格的 div

html - 增加 Wordpress 站点宽度 CSS

javascript - 为什么 jquery 不会将结果放在带有背景颜色设置的 div 中

jquery - 在内容位置更改 Bootstrap 弹出窗口的顶部或底部位置