显示当前子菜单并隐藏其他子菜单

时间:2014-07-29 10:32:59

标签: javascript jquery html

我正在尝试让当前子菜单保持活动状态而隐藏其他子菜单,但却无法理解this关键字的工作原理。目前,由于$('.nav-second-level').show();点击来自任何子菜单的链接,所有子菜单都保持活动状态,我认为我需要修改但无法理解。我是一个jquery Noob。

HTML

<li>
    <a href="#"><i class="fa fa-cog fa-fw"></i> Administration<span class="fa arrow"></span></a>
    <ul class="nav nav-second-level">
        <li>
            <a href="admin-users.php">Users</a>
        </li>
        <li>
            <a href="admin-groups.php">Groups</a>
        </li>
    </ul><!-- /.nav-second-level -->
</li>
<li>
    <a href="#"><i class="fa fa-cog fa-fw"></i> ANother Submenu<span class="fa arrow"></span></a>
    <ul class="nav nav-second-level">
        <li>
            <a href="another-link.php">More Users</a>
        </li>
        <li>
            <a href="another-link.php"> MoreGroups</a>
        </li>
    </ul><!-- /.nav-second-level -->
</li>

JQUERY

$(document).ready(function() {
    var aObj = $('a');
    var found = false;
    for(var i=aObj.length-1; i>=1 && !found; i--) {
        if(document.location.href.indexOf(aObj[i].href)>=0) {
            $(aObj[i]).addClass('active-me');
            found = true;
        }
    }
    var submenulink = $('.nav-second-level > li > a');
    if(submenulink.hasClass('active-me') == true){
        $('.nav-second-level').show();
    }
});

1 个答案:

答案 0 :(得分:1)

试试这个:

$(document).ready(function() {
    // hide all second level
    $('.nav-second-level').hide();

    // show all second level whose anchor has matching href
    $('a').each(function(){
      if(document.location.href.indexOf($(this).attr('href')) > 0)
      {
        // add class to matching anchor
        $(this).addClass('active-me');
        // find its parent 'nav-second-level' and make visible
        $(this).closest('.nav-second-level').show();
      }

    });

    // open submenu on click of main menu
    $('a[href="#"]').click(function(){
       $('.nav-second-level').hide();
       $(this).next('.nav-second-level').show();
    });
});

<强> Demo