最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery: toggle children onclick - Stack Overflow

programmeradmin0浏览0评论

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"><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>

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"><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>
Share Improve this question edited Nov 8, 2010 at 17:17 Nick Craver 631k138 gold badges1.3k silver badges1.2k bronze badges asked Nov 8, 2010 at 17:14 m1k3y3m1k3y3 2,7988 gold badges40 silver badges68 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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();
});
发布评论

评论列表(0)

  1. 暂无评论