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

jquery - Tree using ul li and javascript without plugin - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Mar 29, 2014 at 12:41 DeLeDeLe 2,49020 gold badges92 silver badges135 bronze badges 1
  • Refer This Link This may help you jenkov./books/jquery/tree.html – Manohar singh Commented Mar 29, 2014 at 12:51
Add a ment  | 

1 Answer 1

Reset to default 6

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();       
});

DEMO

发布评论

评论列表(0)

  1. 暂无评论