JavaScript根据当前网址添加类 [英] JavaScript add class depending on current URL

查看:124
本文介绍了JavaScript根据当前网址添加类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的网站导航,我需要添加类'活动'到li元素,取决于它是否匹配当前的URL。

For my website navigation I need to add the class 'active' to the li element depending on if it matches the current 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>


推荐答案

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

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";
        }
    }
}

使用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");
        }
    });
});

这篇关于JavaScript根据当前网址添加类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆