add active class to menu based on url but not to parent

时间:2017-04-10 02:39:44

标签: jquery

i'm having one issues with the following code:

$(function() {
    var links = $('.menu li a');
    var page_url = location.href;

    links.each(function(){
        var link_url = $(this).attr('href'); 

        if(page_url.indexOf(link_url) !== -1) {
            $(this).parent().addClass('active');
        }
    });
});

Basically what is happening i have a side menu on my site:

Main page : /main-page

sub page : /sub-page

sub page : /sub-page

sub page : /sub-page

however when i'm inside the subpage this code is also adding the active class to the main page which in the URL is a parent of the home page example:

example.com/main-page/sub-page

i need to add active class to the sub-page not to the parent.

2 个答案:

答案 0 :(得分:0)

You should split the url as following :

 splitted_url = page_url.split("/");

Get the last part of it (so it will be the last page/sub-page into the url hierarchy based on your url rules), and do your condition with the last part of the url as following :

 if(splitted_url[splitted_url.length - 1].indexOf(link_url) !== -1) {
            $(this).parent().addClass('active');
        }

答案 1 :(得分:0)

我已经使用了上述建议并实施了一些更改,因为它没有正常工作,我不得不拆分链接上的href并匹配它们,然后它工作正常

$(function() {
    var links = $('.menu li a');
    var page_url = location.href;
    var splitted_url = page_url.split("/");

    links.each(function(){
        var link_url = $(this).attr('href');
        var splitted_link = link_url.split("/");
        link_url = splitted_link[splitted_link.length -1];
        if(splitted_url[splitted_url.length - 1] == link_url) {
            $(this).parent().addClass('active');
        }
    });
});