导航/子导航列表,在页面重新加载后如何给被点击的项目添加活动类

3

我有几个嵌套的、隐藏的子导航列表

<ul class="nav">
<li><a href="index.html">Home</a></li>
<li><a class="profile" href="#">Profile</a>
    <ul id="profile">
        <li><a href="company.html">Company</a></li>
        <li><a href="structure.html">Structure</a></li>
        <li><a href="team.html">Team</a></li>
    </ul>
</li>

<li><a class="projects" href="#">Projects</a>
    <ul id="projects">
        <li><a href="chapter.html">Chapter</a></li>
        <li><a href="pblc-trde.html">Pblc Trde</a></li>
        <li><a href="globe.html">Globe</a></li>
        <li><a href="komforte.html">Komforte</a></li>
    </ul>
</li>    

我目前正在使用一些在线找到的jQuery来实现单击时显示/隐藏子导航菜单。我的目标是:

  1. Hopefully clean up the show/hide click function of the sub-nab menus.

  2. When clicking on the sub-nav menu items, the corresponding page that opens, needs to have the sub-nav expanded and give the corresponding menu item active class, so as to let the user know which page they are on.

  3. I am hoping to do this purely in JS/jQuery. The installation of the site will be in WordPress.

    $(document).ready(function () {
    
    $(".profile").click(function () {
        var X = $(this).attr('id');
        if (X == 1) {
            $("#profile").hide();
            $(this).attr('id', '0');
        } else {
            $("#profile").show();
            $(this).attr('id', '1');
        }
    
    });
    
    //Mouse click on nav
    $("#profile").mouseup(function () {});
    
    
    //Document Click
    $(document).mouseup(function () {
        $("#profile").hide();
        $(".profile").attr('id', '');
    });
    
    
    $(".projects").click(function () {
        var X = $(this).attr('id');
        if (X == 1) {
            $("#projects").hide();
            $(this).attr('id', '0');
        } else {
            $("#projects").show();
            $(this).attr('id', '1');
        }
    
    });
    
    //Mouse click on nav
    $("#projects").mouseup(function () {});
    
    //Document Click
    $(document).mouseup(function () {
        $("#projects").hide();
        $(".projects").attr('id', '');
    });
    });
    
    window.onload = function () {
     $("ul#profile li:first").addClass("active");
    };
    
     $(document).ready(function () {
      $("ul#profile").show()
    });
    

你可以结合使用 document.location.href(需要对它进行一些操作)和 $('a[href=something]') 来找到指向当前页面的链接。 - Dave
我在我的答案中添加了代码注释,并进行了一些调整,以改善处理多个子菜单级别的能力。 - Whistletoe
2个回答

1
$(document).ready(function()
{
    // Get the name of the page. Split the URL at the '/':s and get the last part
    // with pop():
    var pageName = (location.pathname).split('/').pop();

    // If we couldn't get a page name, default to index.html:
    if( pageName == '' )
    {
        pageName = 'index.html';
    }

    // Hide ul:s that are children of the navigation:
    $('.nav ul').hide();

    // Event handler for clicks on navigation links:
    $('.nav a').on('click', function()
    {
        // Change visibility for the first ul-child of the current li.
        // $(this) refers to the clicked element.
        $(this).parent('li').find('ul').first().toggle();

        // Hide other sub-menus:
        $(this).parents('li').siblings('li').children('ul').hide();
    });

    // Search through all link elements in the nav menu:
    $('.nav').find('a').each(function(index, value)
    {   
        // Append a '$' to the pagename to make the match()-function search
        // from the end of the href value:
        pageName += '$';

        if( value.href.match(pageName))
        {
            // If the pagename matches the href-attribute, then add the 'active'
            // class to the parent li, and show parent ul:s:
            $(this).parent('li').addClass('active').parents('ul').show();    
        }
    });
});

先生,您真是太棒了!这正是我所希望的运行方式。我会花时间仔细审查您写的内容,并尝试分解和理解它。非常感谢您! - Brandon Leung
我只看到一个小问题。当您打开任一子导航菜单并单击以打开另一个子导航菜单时,它不会隐藏先前的子导航菜单。 - Brandon Leung
点击后编辑以隐藏其他子导航。 - Whistletoe
太好了。我无法感谢你,这个问题困扰了我将近两周。我终于可以继续前进了。=) - Brandon Leung

0

您可以使用Cookie来保存当前打开菜单的值。这将允许在页面加载和浏览器会话之间保存/检索该值。

由于您已经设置了jQuery,因此可以使用jQuery Cookie插件来简化操作。

它的代码非常简单(插件页面上有更多示例)。

$.cookie('open_menu', 'projects'); //Save 'projects' under 'open_menu'
$.cookie('open_menu') //Returns 'projects'

在页面加载时检查值,并在单击菜单之一时保存它。

如果您不想添加任何额外的插件,这里有一些关于JavaScript内置cookie API的文档。

编辑:我已经为您创建了一个JSFiddle示例。Cookie代码似乎无法在那里的沙箱中工作,但该代码应该适用于您,请告诉我是否有任何问题。

$(window).load(function() {
if ($.cookie('show_menu') !== undefined) {
    $('#' + $.cookie('show_menu')).click();
}

$('.nav > li > ul').each(function () {
    //Hide the sub lists
    $(this).hide();
    //Get link with same ID as Class
    var id = $(this).attr('id');
    //When link is clicked
    $('.' + id).click(function () {
        //Get the sub list
        var list = $('#' + $(this).attr('class'));
        //Check if it's currently visible
        if (list.is(':visible')) {
            list.hide(); //Hide list     
            $.cookie('show_menu', ''); //Unset open menu
        } else {
            $('.nav > li > ul').hide(); //Hide all other lists
            list.show(); //Show list
            $.cookie('show_menu', list.attr('class')); //Set open menu
        }
    });
});
});

我对手写js编码还很陌生,因此使用js Cookie对我来说相当困难。我理解需要发生的概念,但不知道如何实现。我知道这可能是一个困难/冗长的问题,但坦白地说,我完全被卡住了,任何示例将不胜感激。 - Brandon Leung
@BrandonLeung 我为您添加了一个JSFiddle,并提供了一些示例代码,应该适用于您的HTML布局。 - Dracs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接