javascript - 根据下拉选项显示/隐藏

标签 javascript jquery html css

我正在使用 Jquery 根据用户在下拉列表中选择的内容显示/隐藏 div。

我的 HTML:

<select>
   <option value='test'>Test</option>
   <option value='example'>Example</option>
   <option value='blah'>Blah</option>
</select>
<div data-show="blah">Should be shown when blah</div>
<div data-hide="example">Should be hidden when example</div>

我的 Jquery(在 coffeescript 中):

$("select").on "change", () ->
  shows = $('[data-show="' + $(this).val() + '"]')
  hides = $('[data-hides="' + $(this).val() + '"]')

  shows.show()
  hides.hides()

当用户选择正确的选项时,这会起作用,例如 Example。但是当用户返回说 Test 时,它应该返回到默认值。我如何让它发挥作用?

最佳答案

可以使用filter() 设置最终显示并在过滤器之前对整个组执行相反操作

$("select").on("change", function(){
  var value = this.value
  // hide all data-show
  $('[data-show]').hide().filter(function(){
     return $(this).data('show') === value;
  }).show()// only show matching ones
  
 $('[data-hide]').show().filter(function(){
     return $(this).data('hide') === value;
  }).hide()

}).change()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
   <option value='test'>Test</option>
   <option value='example'>Example</option>
   <option value='blah'>Blah</option>
</select>
<div data-show="blah">Should be shown when blah</div>
<div data-hide="example">Should be hidden when example</div>

关于javascript - 根据下拉选项显示/隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51350867/

相关文章:

javascript - getElementsByClassName/Id 返回的数组中元素顺序是否一致?

javascript - 我在这里把问题括起来了吗?或者真的有一个意想不到的标识符? Javascript/jQuery

javascript - 是否有一个 UI 框架来模拟 Mac 应用程序的外观?

javascript - Ajax PHP Follow Script - 数据库中没有存储任何内容

jquery - 如何访问与图像关联的特定 div

html - 在 div 的右侧垂直对齐两个 div

java - 使用java构建Web应用程序时出现外文字母问题

javascript - 错误: React Hook "useRouter" - nextJs/javascript app not building

javascript - 目前哪些浏览器支持 JavaScript 的 'let' 关键字?

javascript - 如何让 window.showmodaldialog 在 chrome 37 中工作?