问题
I'm trying to create a nav of links that correspond to different divs in the page, and when you click on the link, it hides all the other divs and slideDown the respective div. I am almost there, but as you can see, it only seems to work on anything that isn't a nested div. (So if I include just text inside that section or p tags or anything else, it will show, but not the children divs.) My code is here: http://jsfiddle.net/DScMX/16/
Furthermore, I want to be able to display the latest year (in my example) when the page is loaded, and then when clicking on each year, as mentioned, it hides what's on the page and displays the correct section.
<div id="years_links">
<a href="#" id="2013">2013</a> |
<a href="#" id="2012">2012</a> |
<a href="#" id="2011">2011</a>
</div>
<div id="yearscontent">
<div id="2013">
<pclass='item'>some 2013 stuff</p>
</div>
<div id="2012">
<div class='item'>some 2012 stuff</div>
</div>
<div id="2011">
<div class='item'>some 2011 stuff</div>
</div>
</div>
and the js
$(document).ready(function() {
var yearscontent = $('#yearscontent');
$('#yearscontent div').hide();
$('#years_links a').click(function() {
var year = $(this).attr('id');
$('#yearscontent div').slideUp(300);
$('#yearscontent #'+year).slideDown(300);
});
});
回答1:
$('#yearscontent div')
selects all divs below #yearscontent
. If you use $('#yearscontent > div')
, it will select only the direct descendant of #yearscontent
.
Also, element id's need to be unique, so you'll need to rework your html/script a little bit. I would use classes instead.
Updated fiddle: http://jsfiddle.net/N5euG/
Update to answer your question in the comments
Consider this html:
<div id="topDiv">
<div id="div1">
<div id="div2">
<div id="div3"></div>
</div>
</div>
</div>
<div id="div4"></div>
#topDiv div
will select #div1
, #div2
, and #div3
. Any div
s within #topdiv
#topDiv > div
will select only #div1
. Just the direct descendant of #topDiv
.
回答2:
I added in some CSS so and an "active" class so that your slide up and down isn't jittery.
#yearscontent div:nth-child(1n+2) {
display:none;
}
http://jsfiddle.net/N5euG/8/
来源:https://stackoverflow.com/questions/17109582/jquery-animation-on-nested-divs