简体   繁体   中英

Add active Menu or Navigation class based on URL

I've added an active class to my menu items. However my current implementation is adding the class to all list menu items as opposed to whatever the current page is.

Please let me know if there is an issue with my current code, and what I can do to achieve the desired outcome.

<ul id="menu_items">
 <li class="has-sub"><a href="/collections">STORE</a></li>
 <li><a href="/collections">RESEARCH</a></li>
 <li><a href="/collections">INFO</a></li>
</ul>

$(function(){
        var current = location.pathname;
        $('#menu_items li a').each(function(){
            var $this = $(this);
            // if the current path is like this link, make it active
            if($this.attr('href').indexOf(current) !== -1){
                $this.addClass('active');
            }
        })
    })  

.active {text-decoration:underline;}

Okay, Try this way, hope it will work

<ul id="menu_items">
<li><a href="#index">Index</a></li>
 <li class="has-sub"><a href="#store">STORE</a></li>
 <li><a href="#research">RESEARCH</a></li>
 <li><a href="#info">INFO</a></li>
</ul>
</html>

<Script>
 $("#menu_items li").bind("click", function(e){

 $("li").click(function() {
        $(this).siblings().find("a").removeClass("active");
        $(this).find("a").addClass("active")
    })
 })

</Script>

Please Check the URLs, All the Links are "/collections"

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