Bootstrap在加载时折叠

Shu*_*med 4 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(' > 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();
});
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/jhfrench/GpdgF/

用于递归可折叠菜单.它完美地运作.但是我需要最初折叠的菜单,即页面加载并仅在单击时展开.

我的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);
?> 
Run Code Online (Sandbox Code Playgroud)

Aru*_*hny 11

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

.tree li ul > li {
    display: none;
}
Run Code Online (Sandbox Code Playgroud)

演示:小提琴

或者在页面加载时隐藏子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();
    });
});
Run Code Online (Sandbox Code Playgroud)

演示:小提琴