开发者

Highlight current url in menu ith jquery

开发者 https://www.devze.com 2023-02-09 14:02 出处:网络
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\");

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
0

精彩评论

暂无评论...
验证码 换一张
取 消