使用 jQuery 选择显示/隐藏多个 DIV [英] Show/Hide multiple DIVs with Select using jQuery
问题描述
我与以下问题中的人的情况基本相同:
I essentially have the same situation as the person in the following question:
通过在 Google 中进行广泛搜索,我找到了几种不同的方法,人们声称他们的方法在这些方法中有效.我还没有让任何人正常工作.我对 jQuery 的了解还不够充分,无法完全理解如何从头开始编写它,因此我现在依赖于非常好的示例.
Through extensive searching within Google I was able to come up with several different methods in which people claim their method works. I have yet to get any to work correctly yet. I don't yet know enough about jQuery to fully understand how to write this from scratch, thus I rely on really good examples for now.
我一直在尝试使用的(基于我发现并尝试过的示例)是这样的:
What I've been trying to work with (based on examples I've found and tried) is this:
<script type="text/javascript">
(document).ready(function() {
('.box').hide();<br/>
('#dropdown').change(function() {
('#divarea1')[ ($(this).val() == 'area1') ? 'hide' : 'show' ]()
('#divarea2')[ ($(this).val() == 'area2') ? 'hide' : 'show' ]()
('#divarea3')[ ($(this).val() == 'area3') ? 'hide' : 'show' ]()
});
});
</script>
<form>
<select id="dropdown" name="dropdown">
<option value="0">Choose</option>
<option value="area1">DIV Area 1</option>
<option value="area2">DIV Area 2</option>
<option value="area3">DIV Area 3</option>
</select>
</form>
<div id="divarea1" class="box">DIV Area 1</div>
<div id="divarea2" class="box">DIV Area 2</div>
<div id="divarea3" class="box">DIV Area 3</div>
- 注意:为了在此消息中正确显示,我在 html 周围使用括号而不是小于号和大于号.
- 第一次加载时未选择任何内容 => 不显示 DIV.
- 当我选择 DIV 区域 1 => 显示 DIV 区域 2 和 3 时.
- 当我选择 DIV 区域 2 => 显示 DIV 区域 1 和 3 时.
- 当我选择 DIV 区域 3 => 显示 DIV 区域 1 和 2 时.
当我测试这个时我得到了什么:
What I get when I test this:
我的大脑被炸了一天.我该怎么做才能解决这个问题?
My brain is fried for the day. What can I do to fix this?
推荐答案
我会这样做:
<script type="text/javascript">
$(document).ready(function(){
$('.box').hide();
$('#dropdown').change(function() {
$('.box').hide();
$('#div' + $(this).val()).show();
});
});
</script>
<form>
<select id="dropdown" name="dropdown">
<option value="0">Choose</option>
<option value="area1">DIV Area 1</option>
<option value="area2">DIV Area 2</option>
<option value="area3">DIV Area 3</option>
</select>
</form>
<div id="divarea1" class="box">DIV Area 1</div>
<div id="divarea2" class="box">DIV Area 2</div>
<div id="divarea3" class="box">DIV Area 3</div>
这篇关于使用 jQuery 选择显示/隐藏多个 DIV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!