JavaScript add class depending on current URL

前端 未结 2 1222
故里飘歌
故里飘歌 2020-12-17 05:01

For my website navigation I need to add the class \'active\' to the li element depending on if it matches the current URL.

Nav HTML:

2条回答
  •  醉酒成梦
    2020-12-17 05:45

    I think, in this case, is better change in server side.

    Using javascript you can do:

    var target = 0;
    switch( window.location.pathname )
    {
        case "/tagged/Review":
            target = 1;
            break;
    
        case "/tagged/First_Look":
            target = 2;
            break;
        /* add other cases */
    }
    
    document.getElementById("nav").getElementByTagName("li")[target].classList.add("active");
    

    Put the code after loaded DOM.

    If jquery, you can use:

    var target = 0;
    switch( window.location.pathname )
    {
        case "/tagged/Review":
            target = 1;
            break;
    
        case "/tagged/First_Look":
            target = 2;
            break;
        /* add other cases */
    }
    
    $($("#nav li")[target]).addClass("active");
    

    EDIT

    window.onload or $.ready is the way to know if the document is loaded.

提交回复
热议问题