我正在使用 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/