2013-12-15 19 views
4

摺疊我使用這個腳本引導負載

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

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

遞歸可摺疊菜單。它完美的作品。但是我最初需要摺疊菜單,即當頁面加載並僅在點擊時展開。

我的JS知識很薄弱。但我試過使用toggle();和hide(); ,它導致崩潰和犯規上點擊

下面擴大是遞歸的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); 
?> 

回答

10

您可以添加CSS規則隱藏在開始

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

演示子li元素: Fiddle

或在頁面加載時隱藏子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(); 
    }); 
}); 

演示:Fiddle

+0

的作品。謝謝。有沒有什麼辦法可以讓最後一個孩子的圖標變成'icon-play',這意味着它已經結束了(最後一個孩子)。 –

+0

@sumaise你是指最後一級或每個級別的最後一個孩子 –

+0

@sumaise like http://jsfiddle.net/arunpjohny/FKWE6/2/? –

0

來完成你想要什麼,最簡單的方法是運行一次點擊()處理。

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

編輯:忘了一些代碼