开发者

How to use jquery to add a class an active link

I am currently trying to make a navigation-menu where an active-class is applied to the anchors with hrefs that match the current url, I've found some jquery that gets the job done but on hover when I move the mouse off the item the style goes away even though I have left that active page.

var path = location.pathname;
var home = "/";
$("a[href='" + [path || home] + "']").parents("li").each(function() {   
       开发者_Python百科 $(this).addClass("current_page_item");
});


var aHrefs = $("li a")

$.each(aHrefs, function (i,e) {
    var href = $(e).attr('href');
    var currentHref = top.location.href;

    if ( href == currentHref ) {
         $(e).parents('li.asign-an-li-class-here').addClass('current_page_item');
    }

});

I think this should work. Load this just before . Check any other code you have that messes with the .current_page_item css class.

Forgot the parents() call. You should assign a class name to that li element so it wont give you a false positive any further up the page.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜