首页 > 解决方案 > 当一个选择框选项被选中时做某事,否则使用 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.

标签: jqueryhtmlcss

解决方案


您正在检查该值是否为假,您真的想检查当前值是否不是默认值。您可以通过将当前值与文本“选择”进行比较来做到这一点:

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


推荐阅读