jQuery-如何显示/隐藏带有子DIV的多个DIV [英] jQuery - How to show/hide multiple DIVs with child DIVs
问题描述
我的标记如下(从 http://jsfiddle.net/nick_craver/srg6g修改的代码/):
<div id="maps">
<div class="map-box"><h2>London & South East</h2><a href="#london"><img src="http://dummyimage.com/100x100/000/fff&text=London" /></a></div>
<div class="map-box"><h2>South West, Ireland and Wales</h2><a href="#south-west"><img src="http://dummyimage.com/100x100/000/fff&text=South+West" /></a></div>
<div class="map-box"><h2>South Central & Home Counties</h2><a href="#south-central"><img src="http://dummyimage.com/100x100/000/fff&text=South+Central" /></a></div>
<div class="map-box"><h2>North England, Northern Ireland & Scotland</h2><a href="#north"><img src="http://dummyimage.com/100x100/000/fff&text=North" /></a></div>
<div class="map-box"><h2>Midlands</h2><a href="#midlands"><img src="http://dummyimage.com/100x100/000/fff&text=Midlands" /></a></div>
</div>
<br /><br/>
<div id="areas">
<div id="london">
<div>content london 1</div>
<div>content london 2</div>
</div>
<div id="south-west">
<div>content south west 1</div>
<div>content south west 2</div>
</div>
<div id="south-central">
<div>content south central 1</div>
<div>content south central 2</div>
</div>
<div id="north">
<div>content north 1</div>
<div>content north 2</div>
</div>
<div id="midlands">
<div>content midlands 1</div>
<div>content midlands 2</div>
</div>
</div>
我的JavaScript代码如下:
And my JavaScript code looks like as follows:
$(".map-box a").click(function(e) {
$("#areas div").hide();
$(this.hash).show();
e.preventDefault();
});
$("#areas div").not("#london, #london div").hide();
当用户单击图像时,我想隐藏当前显示的内容,并显示与该图像相关的两个内容,但这不起作用.
When a user clicks on a image, I'd like to hide what's currently displayed and show both contents associated for that image but this doesn't work.
例如
- 用户点击西南"
- 同时显示内容西南1"和内容西南2"
有人能告诉我我在做什么错吗?
Would anybody be able to tell me what I'm doing wrong?
推荐答案
问题是此行上的选择器:
The problem is the selector on this line:
$("#areas div").hide();
这将选择并隐藏所有作为"#areas" div后代的div元素,其中不仅包括ID为"london"等的div,还包括这些div的子级.然后,当您显示基于ID(例如"london")的div时,其子div及其实际内容将保持隐藏.
This is selecting and hiding all div elements that are descendants of the "#areas" div, which includes not just the divs with ids like "london", etc., but those divs' children too. Then later when you show a div based on an id like "london" its child divs with the actual content remain hidden.
尝试以下方法:
$("#areas > div").hide();
同样,对于最初将其隐藏的行:
And similarly for the line that hides them initially:
$("#areas > div").not("#london, #london div").hide();
这将仅隐藏作为"#areas"直接子级的div.当它们被隐藏时,其子项也将被隐藏,但是当您显示一个子项时,其子项也会自动出现.
That will hide only the divs that are direct children of "#areas". While they are hidden their children will be hidden too, but then when you show one its children will automatically appear with it.
演示: http://jsfiddle.net/7s5nP/
这篇关于jQuery-如何显示/隐藏带有子DIV的多个DIV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!