JavaScript add class depending on current URL

前端 未结 2 1202
故里飘歌
故里飘歌 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:27

    If you want to use "pure" ("vanilla") JavaScript, use the following code(assuming that <ul id="nav"> exists):

    window.onload = function() { 
        var all_links = document.getElementById("nav").getElementsByTagName("a"),
            i=0, len=all_links.length,
            full_path = location.href.split('#')[0]; //Ignore hashes?
    
        // Loop through each link.
        for(; i<len; i++) {
            if(all_links[i].href.split("#")[0] == full_path) {
                all_links[i].className += " active";
            }
        }
    }
    

    Using jQuery:

    $(document).ready(function(){
        var full_path = location.href.split("#")[0];
        $("#nav a").each(function(){
            var $this = $(this);
            if($this.prop("href").split("#")[0] == full_path) {
                $this.addClass("active");
            }
        });
    });
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题