jquery: toggle children onclick
what js/jquery code would make below list toggle children when clicking "+" ?
<ul>
<li id="1" parent="0"><a href="#">1</a></li>
<li id="2" parent="0"><a href="#"> + </a><a href="#">2</a>
<ul parent="2">
<li id="23" parent="2"><a href="#">2.1</a></li>
<li id="50" parent="2">&l开发者_开发技巧t;a href="#"> + </a><a href="#">2.2</a>
<ul parent="50">
<li id="123" parent="50"><a href="#">2.50.1</a></li>
</ul>
</li>
</ul>
</li>
</ul>
You can use .toggle()
or .slideToggle()
with .siblings()
, like this:
$("ul a:contains( + )").click(function() {
$(this).siblings("ul").toggle();
});
You can test it out here. Note though your IDs and attributes are invalid, you may want to use data-
attributes here. Also, I suggest giving those +
links a class, to make the selector much more efficient, for example:
<a href="#" class=".toggle"> + </a>
Then binding like this:
$("ul a.toggle").click(function() {
$(this).siblings("ul").toggle();
});
Something like this
$("ul a:contains('+')").click(function () {
var $this = $(this);
$this.siblings("ul").show();
});
精彩评论