I want to toggle the visibility of single subitems by clicking on the parent list-item.
I have a filetree like this:
<div id="browser">
<ul><li class='folder'>Musik
<ul><li class='folder'>Alben
<ul><li class='folder'>100JahreEAV
<ul>
<li class='file'>000_erste_allgemeine_verunsicherung_-_100_jahre_eav-backcover.jpg</li>
<li class='file'>000_erste_allgemeine_verunsicherung_-_100_jahre_eav-frontcover.jpg</li>
<li class='file'>101_alles_gute_eav.mp3</li><li class='file'>102_popstar.mp3</li>
<li class='file'>103_samurai.mp3</li><li class='file'>104_kuess_die_hand_schoene_frau.mp3</li>
<li class='file'>105_coconut_island.mp3</li><li class='file'>106_johnny_i_fahrscheine.mp3</li>
</ul>
</li></ul>
</li></ul>
</li></ul>
</div>
And this is my code so far:
$("div#browser ul li ul").hide();
$("li").click(function() {
if($(this).hasClass('active')) {
$(this).removeClass('active').children().hide();
} else {
$(this).addClass('active').children().show();
}
});
The problem is that all parent list-items are affected if I click anywhere. Can you tell me how to toggle just one item at once?
DEMO — Adding e.stopPropagation();
prevents the event from propagating to nested elements.
Stop the propagation of clicks in inner list items.
$("li").on("click", function( event ) {
event.stopPropagation();
// rest of your logic here
});
When you click on a nested list item, the click event will not travel up the ancestor tree.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.