我有一个标记如下(代码从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代码如下所示:
$(".map-box a").click(function(e) {
$("#areas div").hide();
$(this.hash).show();
e.preventDefault();
});
$("#areas div").not("#london, #london div").hide();
当用户点击图片时,我想隐藏当前显示的内容并显示与该图片相关联的内容,但这不起作用。
如,
有人能告诉我我做错了吗?
答案 0 :(得分:2)
问题是这一行上的选择器:
$("#areas div").hide();
这是选择并隐藏作为“#areas”div的后代的所有div元素,其中不仅包括带有像“london”等等的id的div,而且还包括那些div的子节点。然后当你显示一个基于像“伦敦”这样的id的div时,它的子div与实际内容保持隐藏。
请改为尝试:
$("#areas > div").hide();
同样对于最初隐藏它们的行:
$("#areas > div").not("#london, #london div").hide();
这将只隐藏“#areas”直接子节点的div。虽然他们隐藏了他们的孩子也会被隐藏,但是当你展示一个孩子时,它的孩子会自动出现。