I have a menu but I want to highlight current link with jquery.
var loc = window.location;
var lochref = 开发者_如何学Go$("#topNavigation li a").attr("href");
if(lochref == loc){
$('#topNavigation li a').addClass('currenthover');
}
With above script, there is no any change in "a" class. How can I do this with jquery? Thanks in advance
First off: This is something you should consider doing server side. It's much, much, much more simpler and reliable.
Your code compares only the href of the first link, as attr
returns the property value of the first link. You need to loop over the links to find the right one.
var loc = window.location.href;
$("#topNavigation li a").each(function() {
if(this.href == loc) {
$(this).addClass('currenthover');
}
});
I would either log loc and lochref in the console, or do an alert, to see what the values are, it could be as simple as missing a trailing slash. Other than that the code is valid.
http://jsfiddle.net/loktar/gjZVK/3/
hit run and the 2nd alert should match, and the link will turn red.
I have always used jQuery to highlight the current menu item. Try this:
$(function () {
var loc = window.location;
var pathName = loc.pathname.substring(loc.pathname.lastIndexOf('/') + 1);
$('[href$="' + pathName+ '"]').parent().addClass("active");
});
You missed .href
off the window.location
object. You need to change the first line to:
var loc = window.location.href
精彩评论