问题
I've got a markup as follows (code modified from 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>
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.
e.g.,
- User clicks on "South West"
- Display both "content south west 1" and "content south west 2"
Would anybody be able to tell me what I'm doing wrong?
回答1:
The problem is the selector on this line:
$("#areas div").hide();
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.
Try this instead:
$("#areas > div").hide();
And similarly for the line that hides them initially:
$("#areas > div").not("#london, #london div").hide();
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.
Demo: http://jsfiddle.net/7s5nP/
来源:https://stackoverflow.com/questions/10278914/jquery-how-to-show-hide-multiple-divs-with-child-divs