I'm using the same js as the one answered in this question: https://stackoverflow.com/questions/302955/active....
my problem is, instead of adding the class to a default link i would like to add the class to a link with the same directory.
example: Page2 is in a different directory. a link, outside of the nav, is clicked on that page. when you go to the next page, how can I keep that active class on the Page2 link?
Here's the nav
<div id="nav">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="test/index.html">Page2</a></li>
<li><a href="test2/index.html">Page3</a></li>
</ul>
</div>
Below is my jquery. the first part works perfect the second part is where i'm having trouble:
function markActiveLink() {var currentURL = window.location.toString().split("/");
$("#nav li a").filter(function() {
//alert(currentURL);
开发者_如何学Go return $(this).attr("href") == currentURL[currentURL.length-1];
}).parent().addClass("current");
if($("#nav li").hasClass("current") == false) {
alert(currentURL[currentURL.length-2]);
}
}
markActiveLink();
Thank you in advance!
This should work. Takes into account whole path not only last part of it.
function markActiveLink() {
var path = location.pathname.substring(1);
$('#nav li a[href="' + path + '"]').parent().addClass("current");
if($("#nav li").hasClass("current") == false) {
//whatever e.g. select default
$('#nav li').eq(0).addClass("current");
}
}
markActiveLink();
精彩评论