简体   繁体   中英

Setting active class to current nav page

Im using jquery to set a active class to the current page. I was wondering whether this piece of code will work on larger websites with more complicated urls, or is there a simpler easier way of going about this.

//Active Menu
$(window).load(function(){

//Get and format current page from url.
var currentPage = window.location.pathname.split('/').reverse()[0];

//If needed, add exceptions to 'currentPage' value.
switch (currentPage){

}

//Target and loop through menu list.
$("#main-nav li a").each(function () {
    //if current page is equal to 'href' value of anchor tag. (Reason for the exceptions)
    if (currentPage === $(this).attr('href').split('/').reverse()[0]) {

        //Then add the active class to the closest li tag.
        $(this).closest('li').addClass('active');

    }
});

});

Just worked this out for myself thru much trial and error.

This worked for me :

$(document).context.all['li.id'].classList.add("classname");
$(document).context.all['li.id'].classList.remove("classname");

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