开发者

Add class to child that fits url

I've made a one page layout website, where the menu doesn't show the active/current link, when users come from Google or bookmarked it.

I've made a script that works fine, but as you see.... it look horribly. How can I do this smart??

//Set .active to current page link
    if (location.href.indexOf("#2") != -1) {
        $("#menu li:nth-child(1) a ").addClass("active");
    }
    if (location.href.indexOf("#3") != -1) {
        $("#menu li:nth-child(2) a ").addClass("active");
    }
    if (location.href.indexOf("#4") != -1) {
      开发者_运维百科  $("#menu li:nth-child(3) a ").addClass("active");
    }
    if (location.href.indexOf("#5") != -1) {
        $("#menu li:nth-child(4) a ").addClass("active");
    }
    if (location.href.indexOf("#6") != -1) {
        $("#menu li:nth-child(5) a ").addClass("active");
    }

Thank you in advance...


How about something like:

$("#menu li:nth-child(" + ( location.hash.slice(1) - 1 ) + ") a ").addClass("active");


var m = location.href.match(/#(\d+)/);
if (m) {
  var index = parseInt(m[1]) - 1;
  if (index >= 1)
    $("#menu li:nth-child("+index+") a ").addClass("active");
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜