How to add class based on current url

2019-08-11 10:10发布

问题:

var search_name = location.search;
    if (search_name.search("cate_no=24")  > 0) {
        $(".cate_new a").addClass("active");
    }
});

If current document url is http://abc.com/list.html?cate_no=24, I want to add class "active" into li a.

I searched and found these js code, but it doesn't work. Is it wrong?

回答1:

It's incorrect. search() returns the offset position of a match if a match is found, and -1 if a match isn't found.

As you are checking for whether cate_no=24 contains cate_no=24, it will return 0 if true.

Currently, your conditional checks whether the search() will return > 0, which is not what you want.

What you should be doing is check whether it is greater > -1:

if (search_name.search("cate_no=24") > -1) 

Although, as I mentioned in the first revision of my answer, it would be better and faster to use indexOf() (search() is supposed to be used when dealing with regular expressions, not for simple string searches).

if (search_name.indexOf("cate_no=24") > -1) 


回答2:

search will only gives you the String. that will be in your case ?cate_no=24

So we leave the first part as it is and try to find the desired value in search_name as string.

var search_name = location.search;

This how we can find the index of the desired pattern.

if (search_name.indexOf("cate_no=24") > 0) {
    $(".cate_new a").addClass("active");
}


回答3:

My personal blog is static so I also had to figure out how to do this without PHP or some other server side code.

This bit of code grabs the path of the current URL, e.g. if you are on http://example.com/about, it would return the string '/about/'. From there you write a simple conditional to add a class to the link you select.

var currentURL = window.location.pathname.toString();
console.log(currentURL);

if (currentURL = '/about/') { 
    $('a#about').addClass('active')
} else if (currentURL = '/work/') {
    ...
}

This could be further developed to grab the href attributes from an array of links with a certain class (.nav-items, for example) and add the active class to whichever element has a href equal to the returned string.



回答4:

Try this

<li class="<?php if(isset($_REQUEST['cate_no']) && $_REQUEST['cate_no']=="24") { echo "active";}?>"></li>