Dropdown Div切换2个不同的Divs

时间:2018-08-10 20:45:53

标签: javascript jquery html toggle

我有一个运行良好的现有javascript解决方案,但是遇到了一项新的增强功能,该功能要求我将名为“ alwaysdisplayonselection”的div仅在将下拉选项从默认选项更改为其他选项后才可见。 >

这是工作中的JSFIDDLE

这是HTML代码:

<select name="my-select" class="js-my-select">
  <option value="nothing" selected>Select Color</option>
  <option value="red">Red</option>
  <option value="orange">Orange</option>
  <option value="yellow">Yellow</option>
  <option value="blue">Blue</option>
  <option value="green">Green</option>
</select>
<div class="js-my-image red"></div>
<div class="js-my-image orange"></div>
<div class="js-my-image yellow"></div>
<div class="js-my-image blue"></div>
<div class="js-my-image green"></div>
<div class="js-my-image alwaysdisplayonselection">This is visible once a selection is made, but invisible once the selection is returned to default, or the first dropdown option with "nothing" value.</div>

这是在不同Divs之间切换的javascript:

$(function() {
  var $select = $('.js-my-select'),
    $images = $('.js-my-image');

  $select.on('change', function() {
    var value = '.' + $(this).val();
    $images.show().not(value).hide();
  });
});

如果能使“ alwaysdisplayonselection” div仅显示一次,并且在刷新页面或所选选项的值为“ nothing”后选择并隐藏选项,我将不胜感激。

提前谢谢!

1 个答案:

答案 0 :(得分:1)

您可以在{strong>更改事件内toggle显示可见性:

$('.alwaysdisplayonselection').toggle(this.value != 'nothing');

您更新的fiddle

var $select = $('.js-my-select'),
    $images = $('.js-my-image');

$select.on('change', function () {
    var value = '.' + $(this).val();
    $images.show().not(value).hide();
    $('.alwaysdisplayonselection').toggle(this.value != 'nothing');
});
div {
  display: none;
  height: 50px;
  width: 50px;
}
.red {
  background-color: red;
}
.orange {
  background-color: orange;
}
.yellow {
  background-color: yellow;
}
.green {
  background-color: green;
}
.blue {
  background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select name="my-select" class="js-my-select">
    <option value="nothing" selected>Select Color</option>
    <option value="red">Red</option>
    <option value="orange">Orange</option>
    <option value="yellow">Yellow</option>
    <option value="blue">Blue</option>
    <option value="green">Green</option>
</select>

<div class="js-my-image red"></div>
<div class="js-my-image orange"></div>
<div class="js-my-image yellow"></div>
<div class="js-my-image blue"></div>
<div class="js-my-image green"></div>
<div class="js-my-image alwaysdisplayonselection">This is visible once a selection is made, but invisible once the
    selection is returned to default, or the first dropdown option with "nothing" value.
</div>