简体   繁体   English

在 URL 的基础上添加 active Menu or Navigation class

[英]Add active Menu or Navigation class based on URL

I've added an active class to my menu items.我在我的菜单项中添加了一个active的 class。 However my current implementation is adding the class to all list menu items as opposed to whatever the current page is.但是,我当前的实现是将 class 添加到所有列表菜单项,而不是当前页面是什么。

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"请检查网址,所有链接均为“/collections”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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