【问题标题】:Tree using ul li and javascript without plugin树使用 ul li 和 javascript 没有插件
【发布时间】:2014-03-29 12:41:46
【问题描述】:

我尝试在here 中使用没有插件的 javascript 制作一个简单的树
这是我的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>

还有我的 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");
    }
});

但它只适用于第一级。怎么做,谢谢。

【问题讨论】:

标签: javascript jquery tree


【解决方案1】:

事件冒泡正在发生。使用e.stopPropagation() 阻止它。顺便说一句,您不需要更改/检查显示属性以使任何元素可见/隐藏,只需使用 .toggle().

试试,

$("li").on("click", function (e) {
    e.stopPropagation();
    $(this).children('ul').toggle();       
});

DEMO

【讨论】:

    猜你喜欢
    • 2022-12-20
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    • 2013-12-01
    相关资源
    最近更新 更多