如何使用嵌套的ul列表显示/隐藏div内容

时间:2017-07-24 15:41:23

标签: jquery show-hide nested-lists

我有一个嵌套的ul列表,其中包含用作在同一页面上显示/隐藏隐藏div的导航的链接。嵌套的工作方式类似于手风琴。

隐藏的div的id与其对应的nav链接的href相同。我可以用没有孩子的李显示/隐藏潜水,但是我无法弄清楚如何使这个也适合带孩子的李。

这是我的HTML:

// Nav
<nav class="mtpd-manual-menu">
    <ul>
        <li><a href="#chiefs-preface" class="active">Chief's Preface</a>
        </li>
        <li><a href="#law-enforcement-code-of-ethics">Law Enforecement Code of Ethics</a></li>
        <li><a href="#mission-statement-and-core-values">Mission Statement and Core Values</a></li>
        <li>Law Enforcement Role and Authority
            <ul>
                <li><a href="#100-law-enforcement-authority">100 - Law 
Enforcement Authority</a></li>
                <li><a href="#102-chief-executive-officer">102 - Chief 
Executive Officer</a></li>
                <li><a href="#104-oath-of-office">104 - Oath of Office</a>
                </li>
                <li><a href="#106-policy-manual">106 - Policy Manual</a>
                </li>
            </ul>
        </li>
    </ul>
</nav>

// Div content
<div id="chiefs-preface" style="display: block;">
    <h2>Chief's Preface</h2>
    <p>Div 1 content...</p>
</div>
<div id="law-enforcement-code-of-ethics">
    <h2>Law Enforcement Code of Ethics</h2>
    <p>Div 2 content...</p>
</div>
<div id="mission-statement-and-core-values">
    <h2>Mission Statement and Core Values</h2>
    <p>Div 3 content</p>
</div>
<div id="law-enforcement-role-and-authority">
    <h2>Law Enforcement Role and Authority</h2>
    <div id="100-law-enforcement-authority">
        <h3>100 - Law Enforcement Authority</h3>
        <p>Div 4 content...</p>
    </div>
    <div id="102-chief-executive-officer">
        <h3>102 - Chief Executive Officer</h3>
        <p>Div 5 content...</p>
    </div>
</div>

这是我的jquery:

// Expand Collapse list
$('.mtpd-manual-menu li').click(function(e){
    if( $(this).find('>ul').hasClass('active') ){
        $(this).css('background-image', 'url("/Data/Sites/1/skins/MetroTransitII/images/PlusSmall.gif")').children('ul').removeClass('active').slideUp();
    e.stopPropagation();
    }
    else{
        $(this).css('background-image', 'url("/Data/Sites/1/skins/MetroTransitII/images/MinusSmall.gif")').children('ul').addClass('active').slideDown();
    e.stopPropagation();
    }
});

// Show content based on link clicked.
$('.mtpd-manual-menu a').click(function(e) {
    e.preventDefault();
    $('.left-col div').hide();
    $('.mtpd-manual-menu li a').removeClass('active'); // remove any existing 'active' classes.
    $(this).addClass('active'); // add class to currently active link.
    var id = $(this).attr('href'); // Get href of active link.
    $(id).show(); // Show div with matching id of active link href.
});

1 个答案:

答案 0 :(得分:0)

因此,虽然我的HTML不完整,但我也注意到我不需要嵌套的div。所以删除父div解决了我的问题。