问题
This is the code I am using at the moment to add an active state to an item after your clicked on one of the navigation and the page has been redirected.
I was wondering if there was another way to do it because it works only on my local machine but not on a server.
$(document).ready(function () {
current_page = document.location.href
if (current_page.match(/home/)) {
$("ul#ulMenuNav li:eq(0) a").addClass('navActive');
} else if (current_page.match(/about/)) {
$("ul#ulMenuNav li:eq(1) a").addClass('navActive');
} else if (current_page.match(/location/)) {
$("ul#ulMenuNav li:eq(2) a").addClass('navActive');
} else if (current_page.match(/staff/)) {
$("ul#ulMenuNav li:eq(3) a").addClass('navActive');
} else if (current_page.match(/contact/)) {
$("ul#ulMenuNav li:eq(4) a").addClass('navActive');
} else {
$("ul#ulMenuNav li a").removeClass('navActive');
};
});
回答1:
You can try this: http://jsfiddle.net/jaiprakashsah/thrDq/
var url = document.location.href;
var str = url.substr(0, url.lastIndexOf('/'));
var nUrl = str.substr(str.lastIndexOf('/')+1);
$('ul#ulMenuNav li a:contains('+nUrl+')').addClass('active');
回答2:
How about:
$(document).ready(function () {
var current_page = document.location.href;
$('ul#ulMenuNav li a').removeClass('navActive');
$('ul#ulMenuNav li a[href*="'+current_page+'"]').addClass('navActive');
});
来源:https://stackoverflow.com/questions/14476591/active-state-on-nav-after-page-refresh