简体   繁体   English

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

[英]How to add an active class to an anchor tag based on URL and Vanity URLs?

I have this working minus the part if the URL is www.mysite.com/home/. 如果URL为www.mysite.com/home/,则我需要进行此工作,而不是该部分。 It works if it is www.mysite.com/home/index.aspx, but not if you take off the index.aspx. 如果是www.mysite.com/home/index.aspx,则可以使用,但是如果删除index.aspx,则不能使用。 It also works for all other pages I have - page2.aspx, page3.aspx, etc... 它也适用于我拥有的所有其他页面-page2.aspx,page3.aspx等...

Also, I might do a URL rewrite on the pages (so page2.aspx would be page2 and page3.aspx would be page3) 另外,我可能会在页面上进行URL重写(因此page2.aspx将是page2,page3.aspx将是page3)

How do I adjust the below code to be able to add the class active to the active page. 如何调整以下代码,以便将活动类添加到活动页面。

jQuery: 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 where the class is added: 添加类的HTML:

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

You can simply check for window.location.pathname 您可以简单地检查window.location.pathname

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

Try this 尝试这个

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

If you want to find the link with the same url part that you are looking for you can try this: 如果要查找与您要查找的URL部分相同的链接,请尝试以下操作:

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

Holy Cow figured out how to do the no index! 圣牛想通了如何做无索引! I didn't think this was going to be so hard to get an answer on. 我不认为要找到答案就这么困难。 Still not sure on the vanity bit. 仍然不确定虚荣心。 Might do separate post on that. 可能会对此做单独的帖子。

$(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");
    })
});
});

I know, maybe this is stupid solution, but: 我知道,也许这是愚蠢的解决方案,但是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM