I have headers, and each of those headers has sub items. When I click a header, I want it to toggle viewing or showing the headers contents:
This is what I have so far:
$j('h2').click(function() {
if ($j(this).next().is(":hidden")) {
$j(this).next().show();
} else {
$j(this).next().hide();
}
});
And my HTML look like this:
<ul class="submenu">
<li class="section"><h2>Section One</h2>
<ul>
<开发者_JS百科;li>text</li>
<li>text</li>
<li>text</li>
</ul>
</li>
<li class="section"><h2>Section Two</h2>
<ul style="display: none; overflow-x: visible; overflow-y: visible; ">
<li style="">
text</li><li>
text</li><li>
text</li></ul>
</li>
</ul>
You can do it the way you have it, or use a slide effect using .slideToggle()
, like this:
$('h2').click(function() {
$(this).next().stop(true, true).slideToggle();
});
You can test it here
Or instantly without the slide effect using .toggle()
(test here):
$('h2').click(function() {
$(this).next().toggle();
});
Or a slide + fade effect using .toggle(speed)
(test here), like this:
$('h2').click(function() {
$(this).next().stop(true, true).toggle("fast");
});
In each case the call to .stop()
is to prevent animation queue build-up. This code is for most users where $ == jQuery
, it looks like you're using .noConflict()
though so just replace $
with $j
like your current code has.
Here is a good tutorial on this subject:
http://homework.nwsnet.de/news/ea21_turn-nested-lists-into-a-collapsible-tree-with-jquery
You will have to tweak it a bit if you want to continue to use the <h2>
tags within the lists, but that should be trivial.
精彩评论