如何根据URL和虚荣URL将活动类添加到锚标记?

时间:2014-08-14 18:11:54

标签: javascript jquery html url window.location

如果网址是www.mysite.com/home/,我的工作减去了部分。如果它是www.mysite.com/home/index.aspx,它可以工作,但如果你取下index.aspx则不行。它也适用于我所有的其他页面 - page2.aspx,page3.aspx等...

另外,我可能会在页面上进行URL重写(因此page2.aspx将是page2而page3.aspx将是page3)

如何调整以下代码,以便能够将活动类添加到活动页面。

jQuery的:

$(function() {
    var pgurl = window.location.href.substr(window.location.href
    .lastIndexOf("/")+1);
    $("nav a").each(function(){
        if($(this).attr("href") == pgurl || $(this).attr("href") == '')
        $(this).addClass("active");
    })
});

添加类的HTML:

 <nav class="clearfix">
  <a href="index.aspx">Home</a>
  <a href="page2.aspx">Page2</a>
  <a href="page3.aspx">Page3</a>
</nav>

5 个答案:

答案 0 :(得分:0)

您只需检查window.location.pathname

即可
$(function() {
    $("nav a").each(function(){
        if($(this).attr("href") == window.location.pathname || window.location.pathname == '')
        $(this).addClass("active");
    })
});

答案 1 :(得分:0)

试试这个

var s = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
if(!s)
    document.querySelector("nav > a:first-child").className = "active";
else
    document.querySelector("nav > a[href*='"+s+"']").className = "active";

答案 2 :(得分:0)

如果您想找到与您正在寻找相同网址部分的链接,可以试试这个:

var lookup = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
$("a:regex(href, .*"+ lookup +".*)").addClass('active');

答案 3 :(得分:0)

Holy Cow想出了如何做无索引!我不认为这会很难得到答案。在虚荣心位上仍然不确定。可以单独发帖。

$(document).ready(function() {

// Add active class to menu
$(function() {
    var pgurl = window.location.href.substr(window.location.href
    .lastIndexOf("/")+1);
    $("nav a").each(function(){
        if($(this).attr("href") == pgurl)
            $(this).addClass("active");
        if (pgurl == '')
                $("nav a:first-child").addClass("active");
    })
});
});

答案 4 :(得分:0)

我知道,也许这是一个愚蠢的解决方案,但是:

  var current_url = window.location.hash.substr(1);
  $('.news #' + current_url).addClass('active');
相关问题