Reputation: 2480
I try to make a simple tree using javascript without plugin in here
Here is my html
<ul class="tree">
<li>First Child
<ul>
<li>First Child
<ul>
<li>First Child</li>
<li>Second Child</li>
<li>Third Child</li>
<li>Fourth Child</li>
</ul>
</li>
<li>Second Child</li>
<li>Third Child</li>
<li>Fourth Child</li>
</ul>
</li>
<li>Second Child</li>
<li>Third Child</li>
<li>Fourth Child</li>
</ul>
and my js
$( "li" ).on( "click", function() {
if ($(this).children('ul').css('display') == 'none') {
$(this).children('ul').css("display", "");
} else {
//alert( $( this ).text() );
$(this).children('ul').css("display", "none");
}
});
but it only working with first level. How to do that thanks.
Upvotes: 4
Views: 3887
Reputation: 67207
Event bubbling is happening out there. use e.stopPropagation()
to block that. And by the way you don't need to change/check the display property to make any element visible/hidden, just use
.toggle()
.
Try,
$("li").on("click", function (e) {
e.stopPropagation();
$(this).children('ul').toggle();
});
Upvotes: 6