简体   繁体   中英

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/. It works if it is www.mysite.com/home/index.aspx, but not if you take off the index.aspx. It also works for all other pages I have - page2.aspx, page3.aspx, etc...

Also, I might do a URL rewrite on the pages (so page2.aspx would be page2 and page3.aspx would be page3)

How do I adjust the below code to be able to add the class active to the active page.

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:

 <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

$(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:

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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