简体   繁体   中英

active menu and submenu on a navigation bar

I have a navigation menu as follows

<div id="nav">
<ul>
    <li><a href="<?php echo base_url(); ?>home">HOME</a></li>
    <li><a href="#">Classes</a>
        <ul>
            <li><a href="<?php echo base_url(); ?>class_one">class One</a></li>
            <li><a href="<?php echo base_url(); ?>class_two">Class Two</a></li>
            <li><a href="<?php echo base_url(); ?>class_three">Class Three</a></li>
            <li><a href="<?php echo base_url(); ?>class_four">Class Four</a></li>
        </ul>
    </li>
    <li><a href="<?php echo base_url(); ?>results">Exams</a>
    </li>    
</ul>
</div>
<script>
$(document).ready(function () {
    $("[href]").each(function () {
        if (this.href == window.location.href) {
            $(this).addClass("active");
        }
    });
});
</script>

Apart from the navigation menu I have a script that would show the page on which the user is by changing the color of menu using active class in my css file. So all the main menus except 'Classes' are working fine but what I want is when the user is on any submenu under 'classes' menu to show 'classes' as the active menu instead of its submenus. How can accomplish that?

Add

$(this).parents('li').find('> a').addClass("active");

in the if statement.

This code finds all the parents of the matched element which are li tags, and then finds the direct children of the matched parents which are a tags, and adds the active class to them too

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM