JavaScript根据当前URL添加类

Kri*_*ews 4 javascript css url

对于我的网站导航,我需要将类"active"添加到li元素,具体取决于它是否与当前URL匹配.

导航HTML:

<ul id="nav">
    <div id="wrapper">
        <li><a href="/">Home</a></li>
        <li><a href="/tagged/Review">Reviews</a></li>
        <li><a href="/tagged/First_Look">First Looks</a></li>
        <li><a href="/tagged/Commentary">Commentaries</a></li>
        <li><a href="/tagged/Walkthrough">Walkthroughs</a></li>
        <li><a href="/tagged/Achievement">Achievements</a></li>
    </div>
</ul>
Run Code Online (Sandbox Code Playgroud)

Rob*_*b W 7

如果要使用"纯"("vanilla")JavaScript,请使用以下代码(假设<ul id="nav">存在):

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";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

使用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");
        }
    });
});
Run Code Online (Sandbox Code Playgroud)