繁体   English   中英

如何使用Javascript根据页面URL添加Active类

[英]How to add Active class based on page URL using Javascript

抱歉,如果以前已经解决过这个问题,但是我对JS还是很陌生。
我使用的示例是在此处将基于URL的活动类添加到导航菜单javascript-仅在发出警报时有效
我修改过的JS在这里:

$(function() {
    setTimeout(function(){
        var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
        console.log(pgurl);

        $(".mega_menu ul li a").each(function(){
            if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
            $(this).addClass("active");
        });
    }, 5000);
});

控制台日志正在生成看起来正确的链接,但是活动类未应用于所需的类,我提供了屏幕截图以希望对您有所帮助。 控制台日志,显示URL应将ACTIVE类应用于的NAV元素

先感谢您!

除pgurl外,您的代码没有任何问题。

$(function() {
setTimeout(function(){

 //   var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/")+1);

    var pgurl = window.location.pathname.replace("/","") + window.location.search; //replace first "/" and make it empty

    $("#nav ul li a").each(function(){
          var _this = this;
         //your condition fails here, can you check your pgurl has this value?
         //old - if($(this).attr("href") == pgurl || $(this).attr("href") == '' )  
       // pgurl - hardcoded 'merchandise2.asp?Merchandise_Group1_ID=8' to run the code successfully
        if($(_this).attr("href") == pgurl || $(_this).attr("href") == '' ) {
           $(_this).addClass("active"); 
           console.log(_this)
        }
    });

}, 50); });

请注意:您不应该像这样使用URL获取和提取URL.location.href.substr(window.location.href.lastIndexOf(“ /”)+ 1);

而是参考获取网址详细信息的最简单方法https://www.w3docs.com/snippets/javascript/how-to-get-current-url-in-javascript.html

我感谢大家的帮助。 下面是起作用的代码,很明显,我对JS的理解还有一段路要走:

        $(function() {
            setTimeout(function(){

                var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/")+1);

                console.log(pgurl)

                $("ul.mega_menu li a.mega_menu_with_ul").each(function(){
                      var _this = this;
                      console.log(_this)
                    //your condition fails here, can you check your pgurl has this value?
                    //old - if($(this).attr("href") == pgurl || $(this).attr("href") == '' )  
                    // pgurl - hardcoded 'merchandise2.asp?Merchandise_Group1_ID=8' to run the code successfully
                    if($(_this).attr("href") == pgurl || $(_this).attr("href") == '' ) {
                        $(_this).addClass("active"); 
                        console.log(_this)
                    }
            });

        }, 50); });

我相信我在CSS调用的构造方式以及我对使用Javascript来解决正确元素所需的具体程度的理解上都遇到了问题。

暂无
暂无

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

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