【问题标题】:jQuery collapsible ULjQuery 可折叠 UL
【发布时间】:2013-09-20 09:04:54
【问题描述】:

我正在使用 jQuery 创建一个导航系统。我想要实现的是让父元素在页面加载时可见,而子元素则隐藏。我做的很简单。

但是,当我在其他父元素之间切换时,我希望能够隐藏之前的子元素,这样我一次只能打开一个 <ul>

//user nav
$('.child').hide();
$('.parent').click(function() {
    $(this).find('ul').slideToggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="rightBottom">
<h1 class="boxheadings">Other functions</h1>
<p class="boxp">Click this button to view your current published site in a new window. This will not show your most recent changes until you click the ‘Publish Changes’ button on the right, alternatively click view local to see unpublished changes.</p>
<ul id="usernav">
    <li class="parent">Manage
        <ul class="child">
            <li>child11</li>
            <li>child12</li>
        </ul>
    </li>
    <li class="parent">Subscriptions
        <ul class="child">
            <li>E-Briefings</li>
            <li>E-Briefings Subscriptions</li>
            <li>Knowledge Briefings</li>
        </ul>
    </li>
    <li class="parent">Media Store
        <ul class="child">
            <li>Image Store</li>
            <li>Document Store</li>
            <li>Media Store</li>
        </ul>
    </li>
</ul>
</div>

【问题讨论】:

    标签: jquery html


    【解决方案1】:

    完成。这很简单。我在显示当前 ul 之前隐藏了所有内容。

    见:

    //hide all children initially
    $('.child').hide();
    
    //adding a click handlers to every all parents
    $('.parent').click(function() {
    
       //slide up the children which are open already
       $('.child').slideUp();
    
       //find the child of clicked parent and toggle its visibility
       $(this).find('ul').slideToggle();
    });
    

    【讨论】:

    • 你不能用这个重新折叠最后一个展开的列表,它只是切换它
    【解决方案2】:

    使用这个

    $('.child').hide();
        $('.parent').click(function() {
            $(this).siblings('.parent').find('ul').slideUp();
            $(this).find('ul').slideToggle();
        });
    

    FIDDLE

    【讨论】:

    • 我在尝试回答时错过了find('ul'),否则我会准确回答这个问题。 +1
    【解决方案3】:

    在展开任何ULs 之前,只需折叠所有@s:

    在您执行 slideToggle 之前添加此行:

    $('#usernav').find('ul').slideUp();
    
    $('.child').hide();
    $('.parent').click(function() {
        $('#usernav').find('ul').slideUp();
        $(this).find('ul').slideToggle();
    });
    

    【讨论】:

      猜你喜欢
      • 2017-07-07
      • 2016-11-09
      • 2012-01-14
      • 2017-07-09
      • 2021-02-22
      • 2012-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多