Javascript 引导程序在加载时崩溃

Javascript 引导程序在加载时崩溃,javascript,jquery,twitter-bootstrap,Javascript,Jquery,Twitter Bootstrap,我使用这个脚本 $(function () { $('.tree li:has(ul)').addClass('parent_li').find(' > span').attr('title', 'Collapse this branch'); $('.tree li.parent_li > span').on('click', function (e) { var children = $(this).parent('li.parent_li').find(' > u

我使用这个脚本

$(function () {
$('.tree li:has(ul)').addClass('parent_li').find(' > span').attr('title', 'Collapse this branch');
$('.tree li.parent_li > span').on('click', function (e) {
    var children = $(this).parent('li.parent_li').find(' > ul > li');
    if (children.is(":visible")) {
        children.hide('fast');
        $(this).attr('title', 'Expand this branch').find(' > i').addClass('icon-plus-sign').removeClass('icon-minus-sign');
    } else {
        children.show('fast');
        $(this).attr('title', 'Collapse this branch').find(' > i').addClass('icon-minus-sign').removeClass('icon-plus-sign');
    }
    e.stopPropagation();
});

用于递归可折叠菜单。它工作得很好。但我需要菜单最初折叠,也就是页面仅在单击时加载和展开

我的JS知识很薄弱。但我尝试使用toggle();和隐藏(),它会导致折叠,并且不会在单击时展开

下面是递归php代码

<?php
function listroles($roles)
{
    ?>
    <ul>
    <?php
    foreach($roles as $role)
    {
        ?>
        <li>
            <span><i class="icon-plus "></i> Parent</span> <a href="<?php echo $role['category']->slug; ?>"><?php echo $role['category']->name; ?></a>
            <?php
            if ( ! empty($role['children']))
            {
                listroles($role['children']);
            }
            ?>
        </li>
        <?php
    }
    ?>
    </ul>
    <?php
}

listroles($this->categories_menu);
?> 

  • 父母亲

您可以添加css规则以在开始时隐藏子li元素

.tree li ul > li {
    display: none;
}
演示:

或者在页面加载时隐藏子li元素

$(function () {
    $('.tree li:has(ul)').addClass('parent_li').find(' > span').attr('title', 'Collapse this branch');

    //hide the child li elements
    $('.tree li ul > li').hide();
    $('.tree li.parent_li > span').on('click', function (e) {
        var children = $(this).parent('li.parent_li').find(' > ul > li');
        if (children.is(":visible")) {
            children.hide('fast');
            $(this).attr('title', 'Expand this branch').find(' > i').addClass('icon-plus-sign').removeClass('icon-minus-sign');
        } else {
            children.show('fast');
            $(this).attr('title', 'Collapse this branch').find(' > i').addClass('icon-minus-sign').removeClass('icon-plus-sign');
        }
        e.stopPropagation();
    });
});

演示:

完成所需操作的最简单方法是运行click()处理程序一次

$(function () {
     $('.tree li.parent_li > span').on('click', function (e) {
        $('.tree li:has(ul)').addClass('parent_li').find(' > span').attr('title', 'Collapse this branch');
       //blah blah blah
        e.stopPropagation();
    }).click();
});

编辑:忘记了一些有效的代码。谢谢有没有办法让最后一个孩子的图标成为“图标游戏”,这意味着它的结束(最后一个孩子)。@sumaise你是说最后一个关卡或每个关卡中的最后一个孩子关卡是不可扩展的,因此它意味着结束关卡和更多的扩展关卡level@sumaise为什么不能在html中更改它呢?我使用递归php代码。我将编辑帖子以显示功能