Jquery Add active class to main menu

前端 未结 4 1087
别跟我提以往
别跟我提以往 2020-12-06 21:26

I\'m trying to add dynamic active class to my main menu, but i can\'t able to achieve this,

My jquery is,



        
4条回答
  •  一整个雨季
    2020-12-06 21:55

    This method will check the page URL that the user is visiting, then add the active class in

  • tag.

    HTML

    
    

    JS

    var setActive = function () {
    
        // Get the last item in the path (e.g. index.php)
        let url = window.location.pathname.split('/').pop();
    
        // Add active nav class based on url
        $("#nav ul li a").each(function () {
            if ($(this).attr("href") == url || $(this).attr("href") == '') {
                $(this).closest('li').addClass("active");
            }
        })
    
        // Add the active class into Home if user omit index.php from url
        if (url == '') {
            $("#nav ul li").eq(0).addClass("active");
        }
    };
    
    $(function () {
        setActive();
    });
    

提交回复
热议问题