Toggle (if exists) nested element
HTML:
<ul class="parent">
<li><a href="#">toggler</a>
<ul class="child">
...
</ul>
</li>
</ul>
I'd like to toggle 'child' UL (if it exists) via 'toggler' link. There might me multiple parent>child elements so I'd like to toggle the开发者_C百科 relevant child only.
Thanks in advance for your help.
The UL is not a child to the anchor, but using next()
is simple enough:
$('ul a').click(function() {
$(this).next().toggle();
});
Given your link has an id:
<a id="Mylink" href="#">
The jQuery would be:
$("#MyLink").click(function(){
$(this).siblings('.child').toggle();
});
You could select directly by element and class instead of ID:
$('ul.parent li a')
But ID selectors are generally considered to be faster
The toggle function also accepts a parameter if you wish to animate, e.g.
$(this).siblings('.child').toggle('slow'); /or 'medium', or 'fast'
$(this).siblings('.child').toggle(100); //100 millisecs
A variation to this is slideToggle, with the same parameters.
$(this).siblings('.child').slideToggle('slow');
http://docs.jquery.com/Effects/toggle
$('ul.parent li a').click(function(event) {
$(this).next('ul.child').slideToggle(500);
event.preventDefault();
});
Have you considered instead of using a link there, a <button>
.
$("a.toggler").click(function(){
$(this).parent().children('.child').toggle();
});
$('.parent a').click(function () {
$('.child', this.parentNode).toggle();
});
精彩评论